在好友列表里,选中项变色,其他项恢复原色,鼠标移入选项时变色,移出时除了选中项恢复原色
<html> <head> <meta charset="utf-8"> <title>好友列表选择</title> <style type="text/css"> *{ margin:0 auto; padding:0;} #wai{ width:220px; height:600px; margin-top:50px;} .friends{ width:200px; height:30px; background-color:#00F; margin-top:5px; text-align:center; line-height:30px; color:#fff;} .friends:hover{ cursor:pointer;} </style> </head> <body> <div id="wai"> <div class="friends" xz="0">曹操</div> <div class="friends" xz="0">刘备</div> <div class="friends" xz="0">孙权</div> <div class="friends" xz="0">诸葛亮</div> <div class="friends" xz="0">司马懿</div> <div class="friends" xz="0">周瑜</div> <div class="friends" xz="0">关羽</div> <div class="friends" xz="0">张辽</div> <div class="friends" xz="0">甘宁</div> </div> </body> </html> <script type="text/javascript"> var f = document.getElementsByClassName("friends"); /* 点击选中变色,其他选项恢复原色,自定义属性xz的值变为1,其他选项恢复为0 */ for(var i=0;i<f.length;i++) { f[i].onclick = function() { for(var i=0;i<f.length;i++) { f[i].style.backgroundColor = "#00F"; f[i].setAttribute("xz","0"); } this.style.backgroundColor = "#F60"; this.setAttribute("xz","1"); } } /* 鼠标移入选项变色 */ for(var i=0;i<f.length;i++) { f[i].onmouseover = function() { this.style.backgroundColor = "#F60"; } } /* 鼠标移出根据自定义属性xz的值判断,xz=1移出不变色,xz=0移出恢复原色 */ for(var i=0;i<f.length;i++) { f[i].onmouseout = function() { var xz = parseInt(this.getAttribute("xz")); if(xz==1) { this.style.backgroundColor = "#F60"; } else if(xz==0) { this.style.backgroundColor = "#00F"; } } } </script>
效果初始
选中变色