js實現點擊ul/li等改變背景顏色


今天項目遇到了標題所說的問題,找到一篇很高效的例子,值得學習。

 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循環就解決了我寫了一大堆的問題!

聲明:本例子是在網上找到的一個例子,如有侵權請與我聯系 郵箱:1783096984@qq.com


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM