点击ul/li改变背景颜色

使用一个简单的for循环解决不同的li分别设置不同背景颜色

1.代码

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  <html>
  <head>
      <title>Change.html</title>
      <meta http-equiv="content-type" content="text/html; charset=UTF-8">
      <style>
        body li{
              list-style-type: none;
        }
     </style>
 </head>
 <body>
 <li onclick='setbgColor(this.id)' id=a><small>第一行文字</small></li><br>
 <li onclick='setbgColor(this.id)' id=b><small>第二行文字</small></li><br>
 <li onclick='setbgColor(this.id)' id=c><small>第三行文字</small></li><br>
 <script type=text/javascript>
     function setbgColor(x)
     {
         d=document.getElementsByTagName('li')
         for(p=d.length;p--;){
             if(d[p].id=='a'){d[p].style.backgroundColor='#AA0000'}
             else if(d[p].id=='b'){d[p].style.backgroundColor='#AABB00'}
             else{d[p].style.backgroundColor='#AABBCC'} 
         } 
     }
</script>
</body>
</html>

2.效果图

猜你喜欢

转载自blog.csdn.net/Wang_WY/article/details/107234125