一,使用nextSibling可以方便的找到该节点的兄弟节点,并为其设置属性
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style type="text/css"> .center{ margin: 0px auto; width: 300px; } .center *{ display: block; padding: 3px 0px; } /*//设置过度*/ .sf{ transition:all 0.5s; } </style> <script language="JavaScript"> /* 封装方法通过id寻找节点*/ function $(oId){ return document.getElementById(oId); } /*为节点添加属性*/ function addClass(obj, cn){ var cNames=obj.className; if(cNames.length==0){ obj.className = cn; }else{ obj.className +=(" "+cn); } } /*删除节点中的属性*/ function removeClass(obj,cn){ var cs=obj.className; cs=cs.split(""); for(var i=0;i<cs.length;i++){ if(cs[i]==cn){ cs.splice(i,1) } } } /*通过节点寻找该节点的兄弟节点*/ function nextSibling(obj,name){ var ele=obj.nextSibling; //alert(typeof ele); for (;ele!=null; ele = ele.nextSibling) { /*将获得的值变成大写*/ var nName = ele.nodeName.toLocaleLowerCase(); /* 判断是否是想要的节点*/ if (nName == name) { return ele; } } } function repeatElement(ele){ var obj=nextSibling(ele,"img"); while(obj!=null){ /*alert(typeof obj); alert(obj.nodeName); alert(obj.src);*/ addClass(obj,"sf"); /*鼠标指到事件*/ obj.onmouseover=function(){ this.style.padding="10px 0px"; } /*鼠标移开事件*/ obj.onmouseout=function(){ this.style.padding="3px 0px" } obj=nextSibling(obj,"img"); } } window.onload = function(){ //$("bu").onclick = function(){ repeatElement($("start")) } </script> </head> <body> <div class="center"> <div id="start"></div> <!--<button id="bu">向下</button-->> <img src="n1.jpg" /> <img src="n2.jpg" /> <span>ada</span> <img src="n3.jpg" /> <img src="n4.jpg" /> <img src="n5.jpg" /> <!--<button id="top">向上</button>--> </div> </body> </html>
例: