【问题标题】:Modify CSS variables / custom properties in jQuery在 jQuery 中修改 CSS 变量/自定义属性
【发布时间】:2018-08-09 10:23:07
【问题描述】:

在我的应用程序中,我有一些参数想要使用 jQuery 放入 CSS 变量中。我也想阅读它们。

我在读取 CSS 变量的值时遇到了麻烦,并尝试了很多方法……在我输入问题时,我在“可能已经有你答案的问题”中找到了解决方案。

无论如何,我附上了一个sn-p,因为我需要知道:
⋅⋅⋅ 为什么方法1不起作用?
⋅⋅⋅ 有没有办法使用 jQuery 获取 CSS var 值?

我觉得它缺少一个简单的解决方案来处理 CSS 变量……我错了吗?
当然,如果没有任何办法,我会使用 javascript 解决方案。但我想确定一下。
提前感谢您的任何回答。

// This method doesn't work for writing CSS var.
$(":root").css("--color1", "red");
console.log(".css method on “:root”      :", $(":root").css("--color1"));

// This methods works for writing CSS var:
$(":root")[0].style.setProperty("--color2", "lime");
console.log("[0].style method on “:root” :", $(":root")[0].style.getPropertyValue('--color2'));
#p1 {
  background-color: var(--color1);
}

#p2 {
  background-color: var(--color2);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>

<body id="bodyID">
  <p id="p1">p with background --color1</p>
  <p id="p2">p with background --color2</p>
</body>

<html>

【问题讨论】:

  • setProperty 如果她不存在,则必须创建该属性。好像是这样的
  • 很高兴看到您从上一个问题中考虑它们,不幸的是我迟到了 :) 您已经有了答案 ;)
  • 无论如何,@TemaniAfif,如果我提出另一个问题,那是你的“错”(开玩笑 :))。再次感谢您对我的另一个问题的回答,向我介绍了 CSS 变量,这真的很值得。
  • 欢迎 ;) 我和每个人都这样做了 :) 我抛出了新功能,然后问题开始下雨,这对每个人都有好处,因为这些资源对未来的人会有帮助 ;)

标签: javascript jquery css css-variables


【解决方案1】:

jQuery 仅支持 version 3.2.0 and later 中的 CSS 自定义属性。在 2.x 或更早版本中不支持它们,因此在这些版本中使用 .css() 访问它们将不起作用。如果升级 jQuery 不是一个选项,您将需要使用内置的 style 对象来访问它们。

$(":root").css("--color1", "red");
console.log(".css method on “:root”      :", $(":root").css("--color1"));

$(":root")[0].style.setProperty("--color2", "lime");
console.log("[0].style method on “:root” :", $(":root")[0].style.getPropertyValue('--color2'));
#p1 {
  background-color: var(--color1);
}

#p2 {
  background-color: var(--color2);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<p id="p1">p with background --color1</p>
<p id="p2">p with background --color2</p>

【讨论】:

  • 谢谢 BoltClock,这是我的问题。我在我的应用程序中验证了 jQuery 的版本,它是 3.1.1...
  • @TemaniAfif :如果 sn-p 是最新的,我的代码就会工作,我可能已经注意到自己的问题了!所以,是的,更新它可能会很好。 :)
【解决方案2】:

作为BoltClock mentions in their answer,jQuery 从版本 3.2.0 开始添加了对 CSS 变量的支持。

但如果由于某种原因无法升级到更高版本,您仍然可以extend jQuery's $.fn.css method 使用自定义属性。

所以我尝试实现一个简单的扩展来检查被修改的属性是否是自定义属性 (by checking that it begins with two hyphens)。如果是,则使用纯 JS 修改自定义属性,否则调用 $.fn.css 的原始实现。

(function() {
  var originalFnCss = $.fn.css;
  $.fn.css = function(prop, val) {

    // Check if the property being set is a CSS Variable.
    if (prop.indexOf("--") === 0) {
      if(val) {

        // Set the value if it is provided.
        for(var idx = 0; idx < this.length; idx++) {
          this[idx].style.setProperty(prop, val);
        }
      } else {

        // Get the computed value of the property.
        return window.getComputedStyle(this[0]).getPropertyValue(prop);
      }
    } else {
      return originalFnCss.apply(this, arguments);
    }
  };
}()); 

注意:目前我已经用 jQuery 1.11.12.2.43.1.1 测试了这个扩展,但是如果你发现任何错误,或者如果你有任何错误,请告诉我建议。


现在您只需在导入 jQuery 之后或在调用 $.fn.css 之前的任何时间添加扩展。这是工作的 sn-p:

(function() {
  var originalFnCss = $.fn.css;
  $.fn.css = function(prop, val) {

    // Check if the property being set is a CSS Variable.
    if (prop.indexOf("--") === 0) {
      if(val) {

        // Set the value if it is provided.
        for(var idx = 0; idx < this.length; idx++) {
          this[idx].style.setProperty(prop, val);
        }
      } else {

        // Get the computed value of the property.
        return window.getComputedStyle(this[0]).getPropertyValue(prop);
      }
    } else {
      return originalFnCss.apply(this, arguments);
    }
  };
}()); 

// This method doesn't work for writing CSS var.
$(":root").css("--color1", "red");
console.log(".css method on “:root”      :", $(":root").css("--color1"));

// This methods works for writing CSS var:
$(":root")[0].style.setProperty("--color2", "lime");
console.log("[0].style method on “:root” :", $(":root")[0].style.getPropertyValue('--color2'));
#p1 {
  background-color: var(--color1);
}

#p2 {
  background-color: var(--color2);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>

<body id="bodyID">
  <p id="p1">p with background --color1</p>
  <p id="p2">p with background --color2</p>
</body>

<html>

【讨论】:

    【解决方案3】:

    这是我的直播版本demo -

    // 颜色数组

    var colConfig = [
      "default-bg",
      "hoverbg",
      "activebg",
      "maintxt",
      "subtxt",
      "listtxt"
    ];
    
    let col_1 = ["#ffffff", "#f5f5f5", "#0065ff",'rgba(20, 20, 200, 1)', 'rgba(20, 20, 20, 1)', 'rgba(100, 100, 100, 0.5)'];
    let col_2 = ["#000000", "#5f5f5f", "#6500ff", "#1f1f1f", "#f1f1f1", "#000088"];
    
    $("#default").click(function () {
      changeTh(col_1);
    });
    
    $("#new").click(function () {
      changeTh(col_2);
    });
    
    function changeTh(col) {
      for (let tag in colConfig) { 
        $(":root").css("--" + colConfig[tag], col[tag]);
      }
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-12
      • 1970-01-01
      • 2023-03-09
      • 2018-11-12
      • 1970-01-01
      • 2020-03-16
      • 2017-03-03
      • 2021-05-03
      相关资源
      最近更新 更多