如何在css代码中更改属性背景颜色

时间:2014-04-03 20:22:38

标签: javascript html css

我使用了以下代码,当我点击下一个菜单时,我想要替换旧颜色。

请给我解决方案。单击下一个选项时如何替换旧颜色。

HTML CODE:

    <head>
<title>Untitled Document</title>
</head>
<body>

<script type="text/javascript">
      function ChangeColor(obj) {
         obj.style.backgroundColor = "#bfcbd6";
      }
</script>

<head>
<link rel="stylesheet" href="css/style.css" type="text/css">
<ul id="css3menu1" class="topmenu">
    <li class="topmenu"><a onclick="ChangeColor(this);"  href="#" title="Home" style="width:154px;" >Home <span class="numberend">1</span> </a></li>
    <li class="topmenu"><a onclick="ChangeColor(this);" href="#" title="Product info" style="width:154px;"><span>Product info</span></a>
    </li>
</ul>
</div>   
</body>
</html>

请查看以下链接:http://jsfiddle.net/8JwhZ/1058/

2 个答案:

答案 0 :(得分:0)

DEMO

function ChangeColor(obj) {
    /* Set all the link colors back to the original one */
    var links = document.querySelectorAll('.topmenu a');
    for (i = 0; i < links.length; i++) {
        links[i].style.backgroundColor = "#005984";
    }
    /* Set the color of the selected one */
    obj.style.backgroundColor = "#bfcbd6";
}

答案 1 :(得分:0)

如果我理解你的帖子,你就有jsfiddle的例子。

您可以使用以下内容:

  </head>
  <script>
   $('.menu').click(
      function(){
         $(this).css("background","#bfcbd6")
      }
    )

  </script>
  <body>
  <link rel="stylesheet" href="css/style.css" type="text/css">
    <ul id="css3menu1" class="topmenu">
      <li class="topmenu"><a href="#" title="Home" class="menu" style="width:154px;" >Home <span class="numberend">1</span> </a></li>
      <li class="topmenu"><a href="#" class="menu" title="Product info" style="width:154px;"><span>Product info</span></a>
      </li>
    </ul>

</body>

http://jsfiddle.net/7F7BP/1/