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

相關文章
相關標籤/搜索