源代码:
<!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++) {//移除属性 apname[i].removeAttribute("a");//背景色初始化pname[i].style.backgroundColor = "yellow";}//为变色元素添加属性aa.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>
效果如下:
JS添加、设置属性以及鼠标移入移出事件
原文地址:https://www.cnblogs.com/davis16/p/8379364.html