扫码关注官方订阅号
点哪个就让哪个变成蓝色 同时其它的都变成没有颜色呢 这样写为什么不对?
aaa bbb
认证0级讲师
<!DOCTYPE html><html><head>
<title></title> <style type="text/css"> #p1{width: 200px;height: 100px;} #p1 span{display: inline-block;width:50px;height: 30px; } </style> <script type="text/javascript"> window.onload=function(){ var oSm=document.getElementsByName('sm'); for(i=0;i<oSm.length;i++){ oSm[i].style.backgroundColor=""; oSm[i].onclick=function(){ var _oSm=document.getElementsByName('sm'); for(i=0;i<_oSm.length;i++) { _oSm[i].style.backgroundColor = ""; } this.style.backgroundColor="blue"; } } } </script>
</head><body><p id="p1">
<span name="sm">aaa</span> <span name="sm">bbb</span>
</p></body></html>
因为你点击的时候只执行this.style.backgroundColor="blue";这个
this.style.backgroundColor="blue";
<!DOCTYPE html> <html> <head> <title></title> <style type="text/css"> #p1{width: 200px;height: 100px;} #p1 span{display: inline-block;width:50px;height: 30px; } </style> <script type="text/javascript"> window.onload=function(){ var oSm=document.getElementsByName('sm'); for(var i=0;i<oSm.length;i++){ oSm[i].onclick=function(){ //去掉所有的样式 for(var j=0;j<oSm.length;j++){ oSm[j].style.backgroundColor=''; } //当前的变色 this.style.backgroundColor="blue"; } } } </script> </head> <body> <p id="p1"> <span name="sm">aaa</span> <span name="sm">bbb</span> </p> </body> </html>
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="p1">
</p>
</body>
</html>
因为你点击的时候只执行
this.style.backgroundColor="blue";这个