1.html文件
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Man bites dog</title> <link rel="stylesheet" type="text/css" href="styles/story.css"> </head> <body> <h1>Hold the front page</h1> <p>This first paragraph leads you in.</p> <p>Now you get the nitty-gritty of the story.</p> <p>The most important information is delivered first.</p> <h1>Extra! Extral!</h1> <p>Further developemnts are it here.</p> <p>You can read all about it here.</p> <script type="text/javascript" src="scripts/styleHeaderSiblings.js"></script> </body> </html>
2.css代码
.intro{ font-weight: bold; font-size: 1.2em; }
3.js代码
function addLoadEvent(func) { var oldonload = window.onload; if(typeof window.onload != "function"){ window.onload = func; }else{ window.onload = function(){ oldonload(); func(); } } } function getNextElement(node){ if(node.nodeType == 1){ return node; } if(node.nextSibling){ return getNextElement(node.nextSibling); } return null; } function addClass(element, value){ if(!element.className){ element.className = value; }else{ var newClassName = element.className; newClassName += " "; newClassName += value; element.className = newClassName; } } function styleHeaderSiblings(){ if(!document.getElementsByTagName) return false; var headers = document.getElementsByTagName("h1"); var elem; for(var i = 0; i < headers.length; i++){ elem = getNextElement(headers[i].nextSibling); addClass(elem, "intro"); } } addLoadEvent(styleHeaderSiblings);