好友列表选中
当选中一个人时,该背景颜色改变,移动鼠标,鼠标移上变色,离开变回。
<style type="text/css">
*{ margin:0px auto; padding:0px; font-family:"微软雅黑";}
#wai{ width:100%; height:300px; margin-top:20px;}
#names{ width:300px; height:300px;}
.name{ width:300px; height:50px; background-color:#9FF; text-align:center; line-height:50px; vertical-align:middle; margin-bottom:10px;}
</style>
</head>
<body>
<div id="wai">
<div id="names">
<div class="name" sx="0">付一</div>
<div class="name" sx="0">赵三</div>
<div class="name" sx="0">李四</div>
<div class="name" sx="0">宋五</div>
<div class="name" sx="0">仲六</div>
</div>
</div>
</body>
<script type="text/javascript">
var n = document.getElementsByClassName("name");
//点击变色
for(var i=0; i<n.length; i++){
n[i].onclick=function(){
for(var i=0; i<n.length; i++){
n[i].style.backgroundColor="#9FF";
n[i].setAttribute("sx","0");
}
this.style.backgroundColor="red";
this.setAttribute("sx","1");
}
}
//移动变色
for(var i=0; i<n.length; i++){
n[i].onmouseover=function(){
this.style.backgroundColor="red";
}
}
//离开变回
for(var i=0; i<n.length; i++){
n[i].onmouseout=function(){
var sx = parseInt(this.getAttribute("sx"));
if(sx==1){
this.style.backgroundColor="red";
}
else if(sx==0){
this.style.backgroundColor="#9FF";
}
}
}
</script>
</html>
这道题需要自定义一个属性,当属性值为0时,背景色为原来的颜色,当属性值变为1,背景色变色。
这道题有一种不用JS就可以实现的简单方法:
<style type="text/css">
*{ margin:0px auto; padding:0px; font-family:"微软雅黑";}
#wai{ width:100%; height:300px; margin-top:20px;}
#names{ width:300px; height:300px;}
.name{ width:300px; height:50px; background-color:#9FF; text-align:center; line-height:50px; vertical-align:middle; margin-bottom:10px;}
.name:hover{ background-color:red;!important}
.name:focus{ background-color:red;}
</style>
</head>
<body>
<div id="wai">
<div id="names">
<div class="name" tabindex="1">付一</div>
<div class="name" tabindex="1">赵三</div>
<div class="name" tabindex="1">李四</div>
<div class="name" tabindex="1">宋五</div>
<div class="name" tabindex="1">仲六</div>
</div>
</div>
</body>
在样式中使用“focus”,它的效果同JS里的“onclick”相似,点击时发生的变化,不过这种属性不能直接用在<div>标签上,需要在标签内加入“tabindex”属性才能使用。

浙公网安备 33010602011771号