【问题标题】:How to make jQuery css affect upcoming elements如何让 jQuery css 影响即将到来的元素
【发布时间】:2012-12-29 22:24:34
【问题描述】:

有没有办法让 jQuery(或任何 javascript)更改 CSS 方案,而不仅仅是将样式应用于与描述符匹配的当前元素?

假设我的 css .bla{ width: 200px;} 上有这个。如果我运行$('.bla').css('width', 300);,那么 jQuery 只会将其应用于现有元素。

我想要的是一种使新宽度成为新 .bla 元素的规则的方法。为了做到这一点,如果我继续添加 .bla 元素,那么它们将是 300 宽。

有没有办法做到这一点?

【问题讨论】:

  • 可以以编程方式编辑现有规则。或者,您可以创建一个新的样式表(也以编程方式),它将覆盖该规则,例如通过body .bla { width: 300px }CSSOM standard 定义了提供此功能的 API。
  • 如何添加新的 .bla 元素?
  • 您确实应该考虑将其保留在主样式表中。因此,例如,.wide .bla {width: 300px;} 样式,然后将 .wide 添加到父级。这将使一切保持在一起。
  • @JamesS,它将动态计算,考虑 $('html').width() 并在 resize 事件中重新计算。
  • @ŠimeVidas,它是通过 $.get 调用传入的原始 html。我正在使用 $('#result').append() 插入它。

标签: jquery css


【解决方案1】:

试试这个:

var style = $('<style>body { background: green; }</style>')
$('html > head').append(style);

这取自this链接

【讨论】:

    【解决方案2】:

    当您运行 $('.bla').css('width', 300); 时,这是由于您页面中的某个条件造成的。

    如果将此条件存储在变量中,则每次添加新的匹配元素时都可以检查是否需要修改它们

    var someCondition=false;
    
    /* later in code*/
    $('.bla').css('width', 300);
    someCondition=true;
    
    /* then when add elements*/
    
    var newBla=$('<div class="bla">')
    if( someConditon){
      newBla.css('width', 300);
    }
    

    如果您使用 CSS 和应用类来代替,您可以使用:

    toggleClass( 'bla_300_class', someCondition); /* second arument is boolean to add or remove*/
    

    【讨论】:

      【解决方案3】:

      你可以这样做:

      <html>
      <head>
      <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" ></script>
      <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.8/jquery-ui.min.js"></script>
      </head>
      <body>
      <div class="style">
      <style>.bla{ width: 200px;}</style>
      </div>
      <div id="divs"></div>
      
      </div>
      <button id="adddiv">Add div</button>
      <button id="changeWidth">Click To Change Width</button>
      <script>
      $(function(){
      $("#adddiv").click(function(){
      $("#divs").append('<div class="bla" style="border:1px solid red;height:20px;margin:2px;">');
      });
      $("#changeWidth").click(function(){
      $(".style").html("<style>.bla{width:300px;}</style>")
      });
      });
      </script>
      </html>
      

      你可以在这里JsFiddle在线测试脚本

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-08-01
        • 2017-01-04
        • 1970-01-01
        • 2021-02-10
        • 1970-01-01
        • 2016-07-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多