javascript - 使用 JavaScript 获取元素的自定义 css 属性 (-mystyle)

标签 javascript css

在某些元素具有自定义 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 获得。

在过去,您不得不依靠 data attributes 来存储数据。并通过 JavaScript 自己处理继承。

但是,“自定义属性”,又名“CSS 变量”,已被引入标准并由浏览器实现,~92% support globally as of 2019-05-09 .快速浏览一下,Edge 似乎是最后一个实现的主要浏览器,2017 年 10 月 16 日发布了第 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>

关于javascript - 使用 JavaScript 获取元素的自定义 css 属性 (-mystyle),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8811027/

相关文章:

javascript - instanceof 在 javascript 中的奇怪输出

javascript - 随着用户输入更改输入框文本的颜色

javascript - 向延迟的动态元素添加过渡?

css3 forcus 在 chrome 浏览器中不起作用或者有什么问题?

javascript - 数组和对象是 Javascript 中唯一的非基元吗?

javascript - 如何在 React Native 中运行后台任务?

html - 如何停止 Internet Explorer 6/7 显示悬停子菜单

c# - onmouseover 效果在 asp.net imagebutton 中不起作用

java - 无法切换到主窗口内的浏览器窗口。(Selenium Webdriver)

javascript - 在 Express.js 中提供资源时遇到问题