【问题标题】:Jquery dynamically change CSS theme - force updating of class?Jquery 动态更改 CSS 主题 - 强制更新类?
【发布时间】:2015-04-26 19:59:15
【问题描述】:

我有一个带有 css 主题的网页。当我单击一个按钮时,主题会更改为另一个文件,但当我尝试使用一些新的主题属性时,我发现它们仍未在元素中更新。

css 文件非常简单:

red.css

.square{ background-color:red; }

蓝色.css

.square{ background-color:blue; }

index.html 文件:

<link rel="stylesheet" id="theme" href="red.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

<div id="mydiv" class="square" style="width:100px; height:100px;"></div>
<button id="mybutton">Change Theme!</button>

<script>
$('#mybutton').on('click', function(){
    console.log($('.square').css("background-color"));
    $('#theme').attr('href', 'blue.css');
    console.log($('.square').css("background-color"));
    alert('When this alert runs, square will still be red, even though the css file has already been switched');
});
</script>

此示例可在此处访问:http://herofocus.com/temp/

有没有办法强制刷新 DOM,这样当 Alert 运行时,主题就已经改变了?

【问题讨论】:

  • 当我点击按钮时,我看到颜色立即改变了!你希望它如何工作?
  • 我正在使用 chrome.. 当警报弹出时,颜色仍然是红色.. 我希望它在警报弹出之前更新为蓝色

标签: javascript jquery css dom


【解决方案1】:

只需将 css 更改后的所有内容放在 setTimeout() 中,以便在您的代码运行之前让 DOM 有机会更新。

$('#theme').attr('href', 'blue.css');
setTimeout(function(){
    alert("'When this alert runs, square will be blue!"); 
}, 0);

注意:这取决于blue.css 的加载速度或预加载速度。有关处理 &lt;link&gt; onload 事件事件的更强大(和复杂)的解决方案,请参阅 @S0lll0s answer。

【讨论】:

    【解决方案2】:

    问题不在于 DOM 尚未刷新,而是当您更改 href 时,您的浏览器需要先再次下载 CSS(或者至少对照缓存)。因此,在您打印 CSS 时它尚未加载(因为 JS 在设计上是异步的)。

    相反,您可能希望以更可控的方式加载 CSS 并让回调打印新值,例如参见 https://stackoverflow.com/a/13610128/1598293。

    【讨论】:

      【解决方案3】:

      您的代码运行良好,您所要做的就是让浏览器完全加载。试试这个(未经测试):

      <link rel="stylesheet" id="theme" href="red.css" />
      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
      
      <div id="mydiv" class="square" style="width:100px; height:100px;"></div>
      <button id="mybutton">Change Theme!</button>
      
      <script>
      $(document).ready(function(){('#mybutton').on('click', function(){
          console.log($('.square').css("background-color"));
          $('#theme').attr('href', 'blue.css');
          console.log($('.square').css("background-color"));
          alert('When this alert runs, square will still be red, even though the css file has already been switched');
      });
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多