【问题标题】:how to change the style attribute dynamically如何动态更改样式属性
【发布时间】:2015-04-30 13:09:17
【问题描述】:

这是我的代码,

<html>
<head>
  <style>
   .containerTitle {
     background-color:silver;
     text-align:center;
     font-family:'Segoe UI';
     font-size:18px;
     font-weight:bold;
     height:30px;
   }
  </style>
</head>
<body>
<div id="a"/>
</body>
</html>

如何使用 jquery 更改 containerTitle 样式中的背景颜色..

【问题讨论】:

  • 你的 html 中的 .containerTitle 类在哪里?
  • 还有一点,
    应该是
  • 切换一个类并编写一个包含这两个类的规则,并在样式表中设置您想要的属性。最容易撤消

标签: javascript jquery html


【解决方案1】:

你去:$(".containerTitle").css("background-color","red");

用法示例:

// wait until the DOM tree is loaded
$(document).ready(function(){
  // click event handler on <a> tags
  $("a").click(function() {
    // change the color on click
    $(".containerTitle").css("background-color","red");
  });
});
.containerTitle {
  background: black;
  height:100px;
  width:100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="containerTitle"></div>
<a href="javascript:;" >change color</a>

【讨论】:

  • Hernandez 在您的示例中,您在 div 中使用了类...没有分配类我们如何实现?
  • 嗯,你需要一个标识符,因为如果没有,只更改那个元素会更难。因为您可以使用$("div").css("background-color","red");,但这会改变您页面上每个div 的背景。您可以做的另一件事:$("#idOfParent div").css("background-color","red");,它将更改元素 &lt;x id="idOfParent"&gt; 内每个 div 的背景
【解决方案2】:

试试这个

$(".containerTitle").css(
    "background","#dedede"
);

【讨论】:

    【解决方案3】:

    添加此代码以动态更改样式属性。

    $('.containerTitle').css({'background':'red'})
    

    【讨论】:

      【解决方案4】:

      这样,

      <script>
          $(document).ready(function() {
          $(".containerTitle ").css("background-color","silver");
          });
          </script>
      

      你还应该在代码的 head 部分中添加 js 库:

      <script src="//code.jquery.com/jquery-2.1.3.min.js"></script>  
      

      这个&lt;div id="a"/&gt;应该是这样的,&lt;div id="a" &gt;&lt;/div&gt;

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-02-06
        • 1970-01-01
        • 1970-01-01
        • 2020-03-13
        • 2019-03-14
        • 1970-01-01
        • 2021-02-09
        相关资源
        最近更新 更多