js实现点击ul/li等改变背景颜色

今天项目遇到了标题所说的问题,找到一篇很高效的例子,值得学习。javascript

 1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 2 <html>
 3 <head>
 4     <title>Change.html</title>
 5     <meta http-equiv="content-type" content="text/html; charset=UTF-8">
 6     <style>
 7         body li{
 8             list-style-type: none;
 9         }
10     </style>
11 </head>
12 <body>
13 <li onclick='g(this.id)' id=w><small>文字</small></li><br>
14 <li onclick='g(this.id)' id=i><small>文字</small></li><br>
15 <li onclick='g(this.id)' id=y><small>文字</small></li><br>
16 <script type=text/javascript>
17     function g(x)
18     {
19         d=document.getElementsByTagName('li')
20         for(p=d.length;p--;){
21             if(d[p].id!=x){d[p].style.backgroundColor='#FFFFFF'/*其余*/}
22             else{d[p].style.backgroundColor='#D2D2D2'/*点击的*/} 
23 }
24 }
25 </script> 26 </body> 27 </html>

一个简单的for循环就解决了我写了一大堆的问题!html

声明:本例子是在网上找到的一个例子,若有侵权请与我联系 邮箱:1783096984@qq.comjava

相关文章
相关标签/搜索