簡體   English   中英

使用 JavaScript 獲取元素的自定義 css 屬性 (-mystyle)

[英]Get element's custom css properties (-mystyle) using JavaScript

在某些元素具有自定義 CSS 屬性的應用程序中,有沒有辦法通過 JavaScript 檢索這樣的值?

例如

<div id="myDiv" style="color:#f00;-my-custom-property:upsidedown;" />

我可以通過這兩種方法訪問顏色屬性:

document.getElementById('myDiv').style.getPropertyValue("color")
document.getElementById('myDiv').style.color

但這些不適用於自定義屬性。 這完全支持嗎?

瀏覽器無法理解的 CSS 值將被丟棄,這解釋了為什么-my-custom-property無法通過.style

過去,您將不得不依賴於使用數據屬性存儲數據並通過 JavaScript 自己處理繼承。

然而,“自定義屬性”,又名“CSS 變量”,已被引入標准並由瀏覽器實現,截至 2019 年 5 月 9日,全球支持率約為 92% 乍一看,Edge 似乎是最后一個實現的主要瀏覽器,版本 16 於 2017 年 10 月 16 日發布。

本質上,您需要在元素上設置自定義屬性(例如, --my-custom-property: 'foobar'; ),並且可以使用類似getComputedStyle(your_el).getPropertyValue("--my-custom-property")將返回'foobar' (帶有前導空格)。 請注意前導空格和引號。 它將完全按照提供的值返回值。

例子:

 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>

以下是使用一兩個前導連字符、繼承和不同方法檢索值的一些測試:

 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>

CSS:

:root {
    --custom-property: #000000;
}

Javascript:

var custom_property = window.getComputedStyle(document.body).getPropertyValue('--custom-property').trim()

將無法識別的 CSS 屬性放入style屬性或style.cssText屬性時,將被忽略。

如果要在特定元素上定義屬性,我建議使用data-attributes
HTML:

<div id="myDiv" style="color:#f00;" data-custom-property="upsidedown" />

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");

這實際上現在對於通過 CSS content標簽使用專門的 CSS hack 的所有瀏覽器都是可能的。 這篇文章解釋了如何做到這一點:

http://www.yearofmoo.com/2015/04/cross-browser-custom-css-properties.html

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;

}

您可以使用CSSStyleDeclaration API 來執行此操作:

element.style.setProperty('color', 'black')

您不能使用 data-* 屬性 (html5)? 這至少是有效的,而不是奇怪的黑客攻擊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM