使用 JavaScript 获取元素的自定义 css 属性 (-mystyle)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8811027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get element's custom css properties (-mystyle) using JavaScript
提问by Aaron J Spetner
In an application where certain elements have custom CSS properties, is there any way to retrieve such a value via JavaScript?
在某些元素具有自定义 CSS 属性的应用程序中,有没有办法通过 JavaScript 检索这样的值?
e.g.
例如
<div id="myDiv" style="color:#f00;-my-custom-property:upsidedown;" />
I can access the color attribute via these two methods:
我可以通过这两种方法访问颜色属性:
$('myDiv').style.getPropertyValue("color")
$('myDiv').style.color
But these do not work for custom properties. Is this supported at all?
但这些不适用于自定义属性。这完全支持吗?
采纳答案by 0b10011
CSS values not understood by the browser are discarded, which explains why -my-custom-property
was unavailable via .style
.
浏览器无法理解的 CSS 值将被丢弃,这解释了为什么-my-custom-property
通过.style
.
In the past, you would have had to rely on storing the data with data attributesand dealing with inheritance yourself via JavaScript.
过去,您将不得不依赖于使用数据属性存储数据并通过 JavaScript 自己处理继承。
However, "custom properties", aka "CSS variables", have since been introduced into the standard and implemented by browsers, with ~92% support globally as of 2019-05-09. At a quick glance, Edge seems to have been the last major browser to implement, with version 16 on October 16, 2017.
然而,“自定义属性”,又名“CSS 变量”,已被引入标准并由浏览器实现,截至 2019 年 5 月 9日,全球支持率约为 92%。乍一看,Edge 似乎是最后一个实现的主要浏览器,版本 16 于 2017 年 10 月 16 日发布。
Essentially, you need to set a custom property (eg, --my-custom-property: 'foobar';
) on an element, and it can be accessed with something like getComputedStyle(your_el).getPropertyValue("--my-custom-property")
which would return 'foobar'
(with a leading space). Note the leading space and quotation marks. It will return the value exactly as it was provided.
本质上,您需要--my-custom-property: 'foobar';
在元素上设置自定义属性(例如,),并且可以使用类似getComputedStyle(your_el).getPropertyValue("--my-custom-property")
返回的内容'foobar'
(带有前导空格)来访问它。请注意前导空格和引号。它将完全按照提供的值返回值。
Example:
例子:
console.log(getComputedStyle(document.getElementById("a")).getPropertyValue("--my-custom-property-1"))
console.log(getComputedStyle(document.getElementById("b")).getPropertyValue("--my-custom-property-2"))
#b-div { --my-custom-property-2: 'world' }
<div style="--my-custom-property-1: 'hello'"><h1 id="a">#a 'hello'</h1></div>
<div id="b-div"><h1 id="b">#b 'world'</h1></div>
Here's some testing using one and two leading hyphens, inheritance, and different methods of retrieving the value:
以下是使用一两个前导连字符、继承和不同方法检索值的一些测试:
function log(computed, selector, prop, value) {
let method = computed ? "getComputedStyle(el)" : "el.style"
let method_id = computed ? "computed" : "raw"
// Build first level of list (tag name)
let first = document.querySelector("#" + selector)
if (!first) {
first = document.createElement("li")
first.appendChild(document.createTextNode(selector))
first.setAttribute("id", selector)
first.appendChild(document.createElement("ul"))
document.querySelector("ul").appendChild(first)
}
// Build second level of list (method of style retrieval)
let second = document.querySelector("#" + selector + "-" + method_id)
if (!second) {
second = document.createElement("li")
second.appendChild(document.createTextNode(method))
second.setAttribute("id", selector + "-" + method_id)
second.appendChild(document.createElement("ul"))
first.querySelector("ul").appendChild(second)
}
// Build third level of list (property accessed)
let third = document.querySelector("#" + selector + "-prop" + prop)
if (!third) {
third = document.createElement("li")
third.appendChild(document.createTextNode(prop + ": `" + value + "`"))
third.setAttribute("id", "prop" + prop)
second.querySelector("ul").appendChild(third)
if (value === "") {
third.classList.add("bad")
} else {
third.classList.add("good")
}
}
}
// Uses .style
function getStyleAttr(selector, prop) {
let value = document.querySelector(selector).style.getPropertyValue(prop)
log(false, selector, prop, value)
}
// Uses getComputedStyle()
function getStyleComputed(selector, prop) {
let value = getComputedStyle(document.querySelector(selector)).getPropertyValue(prop)
log(true, selector, prop, value)
}
// Loop through each property for each element and output the value
let selectors = ["article", "h1", "p"]
let props = ["--my-custom-property", "-my-custom-property"]
selectors.forEach(function(selector) {
props.forEach(function(prop) {
getStyleAttr(selector, prop)
getStyleComputed(selector, prop)
})
})
code {
background: #eee;
padding: .2em;
}
.bad {
color: #800;
}
.good {
color: #080;
}
<article class="custom-prop-inheritance" style="--my-custom-property: 'foobar'; -my-custom-property: 'foobar'">
<h1>Title</h1>
<p>Custom properties require two leading hyphens (<code>-my-custom-property</code> <em>never</em> works). Using <code>el.style</code> does not support inheritance. To support both inheritance and custom properties, you must use <code>getComputedStyle(<b>el</b>)</code> along with two leading hyphens on the custom property (eg, <code>--my-custom-property</code>).</p>
</article>
<ul></ul>
回答by M.Adam
CSS:
CSS:
:root {
--custom-property: #000000;
}
Javascript:
Javascript:
var custom_property = window.getComputedStyle(document.body).getPropertyValue('--custom-property').trim()
回答by Rob W
Non-recognised CSS properties will be ignored when put within the style
attribute, or in the style.cssText
property.
将无法识别的 CSS 属性放在style
属性中或属性中时将被忽略style.cssText
。
If you want to define a property at a specific element, I recommend data-attributes:
HTML:
如果你想在特定元素上定义一个属性,我推荐data-attributes:
HTML:
<div id="myDiv" style="color:#f00;" data-custom-property="upsidedown" />
JavaScript:
JavaScript:
//jQuery's method to retrieve value:
$("#myDiv").data("custom-property");
//jQuery, without parsing:
$("#myDiv").attr("data-custom-property");
// Modern browsers, native JS:
document.getElementById("myDiv").dataset["custom-property"];
// Older browsers, native JS:
document.getElementById("myDiv").getAttribute("data-custom-property");
回答by matsko
This is actually now possible for all browsers using a specialized CSS hack via the CSS content
tag. This article explains how to do it:
这实际上现在对于通过 CSScontent
标签使用专门的 CSS hack 的所有浏览器都是可能的。这篇文章解释了如何做到这一点:
http://www.yearofmoo.com/2015/04/cross-browser-custom-css-properties.html
http://www.yearofmoo.com/2015/04/cross-browser-custom-css-properties.html
回答by yk77500
function getCustomCssProperty(elementID, propertyName){
var style = document.getElementById(elementID).getAttribute("style");
var entries = style.split(";");
for (var i=0; i<entries.length; i++){
var entry = entries[i].split(":");
if(entry[0] == propertyName){
return entry[1];
}
}
return null;
}
回答by Sven Bieder
You can't use data-* attributes (html5)? That would at least be valid and not a strange hack.
您不能使用 data-* 属性 (html5)?这至少是有效的,而不是奇怪的黑客攻击。