1.利用DOM找出文档中的所有h1元素,在找出紧跟在每个h1元素后面的那个元素,并把样式添加给它。
story.html
Man bites dog
Hold the front page
This first paragraph leads you in.
Now you get the nitty-gritty of the story.
The most important information is delivered first.
Extra! Extra!
Further developments are unfolding.
You can read all about it here.
addLoadEvent.js
function addLoadEvent(func){
var oldonload=window.onload;
if(typeof window.onload!='function'){
window.onload=func;
}else{
window.onload=function(){
oldonload();
func();
}
}
}
styleHeaderSiblings.js
function styleHeaderSiblings(){
if(!document.getElementsByTagName)return false; //检查兼容性
var headers=document.getElementsByTagName("h1"); //找到所有的h1元素
var elem;
for(var i=0;i
2.表格交替改变他们的背景色,形成斑马线效果
itinerary.html
Cities
Itinerary
When
Where
June 9th
Portland,OR
June 10th
Seattle,WA
June 12th
Sacramento,CA
format.css
body{
font-family:"Helvetica","Arial",sans-serif;
background-color:#fff;
color:#000;
}
table{
margin:auto;
border:1px solid #699;
}
caption{
margin:auto;
padding:.2em;
font-size:1.2em;
font-weight:bold;
}
th{
font-weight:normal;
font-style:italic;
text-align:left;
border:1px dotted #699;
background-color:#9cc;
color:#000;
}
th,td{
width:10em;
padding:.5em;
}
stripeTables.js
function stripTables(){
if(!document.getElementsByTagName)return false; //检查兼容性
var tables=document.getElementsByTagName("table"); //找table元素
var odd,rows;
for(var i=0;i
以及addLoadEvent.js,充实文档内容的displayAbbreviations.js
鼠标指针悬停在某个表格上方时,把该行的文本加黑加粗
highlightRows.js
function highlightRows(){
if(!document.getElementsByTagName)return false;
var rows=document.getElementsByTagName("tr");
for(var i=0;i
再在ltinerary.html添加
通过css而不是DOM去设置样式,确保网页的表示层和行为层分离的更加彻底
更新stripeTables.js
rows[j].style.backgroundColor="#ffc";
改为
addClass(rows[j],"odd");
需要给一个元素追加新的class时,调用addClass函数
addClass.js
function addClass(element,value){
if(!element.className){ //检查className值是否为null
element.className=value; //为null,则赋新值
}else{ //否则,旧值加新值(追加class属性)
newClassName=element.className;
newClassName+=" ";
newClassName+=value;
element.className=newClassName;
}
}
结果不变,但CSS与DOM分离的更加彻底。
对函数进行抽象,有利于变得更加通用
eg:增加两个参数tag和theclass
function styleElementSiblings(tag,theclass){
if(!document.getElementsByTagName)return false;
var elems=document.getElementsByTagName(tag);
var elem;
for(var i=0;i