var sfEls = document.getElementById("nav").getElementsByTagName("li");
for (var i=0; i<sfEls.length; i++) {
sfEls[i].onmouseover=function() {
this.className+=(this.className.length>0? " ": "") + "sfhover";
}
sfEls[i].onMouseDown=function() {
this.className+=(this.className.length>0? " ": "") + "sfhover";
}
sfEls[i].onMouseUp=function() {
this.className+=(this.className.length>0? " ": "") + "sfhover";
}
sfEls[i].onmouseout=function() {
this.className=this.className.replace(new RegExp("( ?|^)sfhover\\b"), "");
}
}
这是个下拉菜单代码来的,麻烦大家解释下
代码功能我能猜得出来,但 this.className+=(this.className.length>0? " ": "") + "sfhover";
this.className=this.className.replace(new RegExp("( ?|^)sfhover\\b"), "");
这两段代码的写法我不是很懂,能详细说清吗
找出文档中id为nav的标签下的li标签for (var i=0; i<sfEls.length; i++) {
遍历所有这样的标签sfEls[i].onmouseover=function() {
this.className+=(this.className.length>0? " ": "") + "sfhover";
}
sfEls[i].onMouseDown=function() {
this.className+=(this.className.length>0? " ": "") + "sfhover";
}
sfEls[i].onMouseUp=function() {
this.className+=(this.className.length>0? " ": "") + "sfhover";
}
这三句是说当鼠标处于over、Down、Up三种状态时改变相应li标签的类名,如果原li标签无类名则改为sfover,如果有加上空格和sfover,意图是通过在css里设置.xxx sfover={xxxxxx}来改变标签的视觉效果,实现翻转器的效果sfEls[i].onmouseout=function() {
this.className=this.className.replace(new RegExp("( ?|^)sfhover\\b"),
"");
这句设置鼠标离开的视觉效果,简单说来和上面的过程相反,用正则的找出sfhover的匹配、删除,是鼠标离开后回到原来的显示效果。
this.className+=(this.className.length>0? " ": "") + "sfhover"; 当this.className为空的时候,this.className=this.className+""+"sfhover"
不为空的时候 this.className=this.className+" "+"sfhover"我主要是不理解""和" "的作用,你能说下吗
this.className+=(this.className.length>0? " ": "") + "sfhover"; 当this.className为空的时候,this.className=this.className+""+"sfhover"
不为空的时候 this.className=this.className+" "+"sfhover" 我主要是不理解""和" "的作用,你能说下吗
加空格是因为,一个每个标签是可以有多个class的, <element class="c1 c2">,中间用" "分隔