jQuery 有办法获取和设置 CSS 变量的值吗? ( MDN - Using CSS variables )
我已经尝试使用普通的 css 函数 $(".element").css("--varname", 1)
,但它不起作用。
我可以使用普通的 DOM 函数,但我不想将其与 jQuery 混合使用:
element.style.getPropertyValue("--varname");
element.style.setProperty("--varname", value);
我在 transform
中使用这个变量,所以使用这个变量得到的结果是一个 matrix3d()
字符串。我需要在 JS 中获取一些计算的值
最佳答案
你可以使用$.cssHooks
, $.support
(function($) {
// First, check to see if cssHooks are supported
if (!$.cssHooks) {
// If not, output an error message
throw (new Error("jQuery 1.4.3 or above is required"
+ " for this plugin to work"));
}
// Wrap in a document ready call, because jQuery writes
// cssHooks at this time and will blow away your functions
// if they exist.
$(function() {
$.cssHooks["mainBgColor"] = {
get: function(elem, computed, extra) {
// Handle getting the CSS property
return elem.style.getPropertyValue($.support["mainBgColor"])
|| window.getComputedStyle(elem)
.getPropertyValue($.support["mainBgColor"])
},
set: function(elem, value) {
// Handle setting the CSS value
elem.style.setProperty($.support["mainBgColor"], value);
return elem
}
};
$.support["mainBgColor"] = "--main-bg-color";
console.log($("h1").css("mainBgColor")); // `"brown"`
$("h1").css("mainBgColor", "green");
console.log($("h1").css("mainBgColor")); // `"green"`
});
})(jQuery);
h1 {
--main-bg-color: brown;
}
h1 {
background-color: var(--main-bg-color);
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<h1>Hello Plunker!</h1>
<script>
</script>
</body>
</html>
关于javascript - 获取或设置 CSS 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38314608/