JS添加、设置属性以及鼠标移入移出事件
源代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{
margin: 0px auto;
}
#wk{
width:100px;
}
.pname{
width: 100px;
height: 50px;
line-height: 50px;
text-align: center;
background-color: yellow;
margin: 2px ;
}
</style>
</head>
<body>
<div id="wk">
<div class="pname" onmouseover="ChangeColor(this)"
onclick="ClickChange(this)"
onmouseout="KeepColor(this)">
小花
</div>
<div class="pname" onmouseover="ChangeColor(this)"
onclick="ClickChange(this)"
onmouseout="KeepColor(this)">
小白
</div>
<div class="pname" onmouseover="ChangeColor(this)"
onclick="ClickChange(this)"
onmouseout="KeepColor(this)">
小明
</div>
</div>
</body>
<script type="text/javascript">
//获取要改变样式的元素
var pname = document.getElementsByClassName("pname");
//鼠标点击事件,移入变色
function ClickChange (a) {
for (var i=0; i<pname.length; i++) {
//移除属性 a
pname[i].removeAttribute("a");
//背景色初始化
pname[i].style.backgroundColor = "yellow";
}
//为变色元素添加属性a
a.setAttribute("a",1);
//鼠标移入,改变背景色
a.style.backgroundColor = "red";
}
//鼠标移入事件,点击改变背景色
function ChangeColor (a) {
//循环添加背景色
for (var i=0; i<pname.length; i++) {
//清样式
if (pname[i].getAttribute("a")!=1){
pname[i].style.backgroundColor ="yellow";
}
}
a.style.backgroundColor = "red";
}
//添加鼠标移出事件
function KeepColor(a) {
for (var i=0; i<pname.length; i++) {
//清样式
if (pname[i].getAttribute("a")!=1)
{
pname[i].style.backgroundColor ="yellow";
}
}
}
</script>
</html>
效果如下:


浙公网安备 33010602011771号