【问题标题】:Is it possible to change CSS Variables globally via jQuery?是否可以通过 jQuery 全局更改 CSS 变量?
【发布时间】:2020-08-18 01:19:20
【问题描述】:

我想使用 CSS 变量并通过 jQuery 全局更改它们。

这里有一些代码:

$("div").click(function() {
  // Change globally "--text_color: rgb(0, 0, 255);" to for example "--text_color: rgb(0, 255, 255);"
});
:root {
  --text_color: rgb(0, 0, 255);
}

div {
  color: var(--text_color);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>Hello</div>

有没有办法对此进行编程?

非常感谢您的帮助!

【问题讨论】:

标签: javascript jquery


【解决方案1】:

由于变量是全局变量,因此您可以在样式中的任何位置设置它,并且值将被更新。

$("div").click(function() {
    this.setAttribute("style", "--text_color: rgb(255, 255, 255);");
});

但是,我建议您不要修改全局变量,而是更新类名。列出根变量并在不同的类中使用不同的值:

:root {
    --text-color1: rgb(0, 0, 255);
    --text-color2: rgb(0, 255, 255);
}
.class1 {
    color: var(--text-color1);
}
.class2 {
    color: var(--text-color1);
}

现在您可以点击更改类名:

$("div").click(function() {
   this.className = "class2";
});

【讨论】:

    【解决方案2】:

    这已经被问及回答了。

    Change CSS variable using jQuery

    但要回答你的问题,

    $(this).get(0).style.setProperty(variable, value);
    

    【讨论】:

      【解决方案3】:

      在头部附加一个&lt;style&gt; 标签。为了进一步操作,给它一个 id 以便您可以轻松删除或修改它

      const rules = `:root {
        --text_color: rgb(0, 0, 255);}
      div {
        color: var(--text_color);
      }`
      
      
      $("div").click(function() {
        $('<style>', {text: rules}).appendTo('head');
      });
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      
      <div>Hello</div>

      【讨论】:

        【解决方案4】:

        也许可以尝试通过addClass()link更改课程

        如果你需要改回来,你可以使用removeClass()link

        这样称呼(或多或少)

        $(document).ready(function(){
          $("button").click(function(){
            $("h1, h2, p").addClass("blue");
            $("div").addClass("important");
        

        与 CSS 类似

        .important {
          font-weight: bold;
          font-size: xx-large;
        }
        
        .blue {
          color: blue;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-10-03
          • 2013-08-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-01-03
          相关资源
          最近更新 更多