不带源元素的JavaScript getComputedStyle

JavaScript getComputedStyle without source element?

本文关键字:JavaScript getComputedStyle 元素      更新时间:2023-09-26

本质上,我试图使用getComputedStyle来获取属性值,而无需(直接)访问元素。请阅读下面的描述以了解更多详细信息。

这很难解释,所以如果你不明白,请告诉我。

这是我的CSS代码:

.yScrollButton{
    background-color:#aaa;
    width:100%;
    position:absolute;
    top:0;
    min-height:30px;
}
.xScrollButton{
    background-color:#aaa;
    height:100%;
    position:absolute;
    top:0;
    min-width:30px;
}

链接到这些类的元素是用JavaScript生成的。如何在不使用元素查找min-width:30px;min-width:30px;属性值的情况下获取它们。通常在这种情况下,您使用getComputedStylehttps://stackoverflow.com/a/18676007/3011082但在这种情况下,我无法获得计算样式的源元素(见下面的示例)!

var yourDiv = document.getElementById("some-id");
getComputedStyle(yourDiv).getPropertyValue("margin-top")

同样,这很令人困惑,所以如果你不明白,请告诉我:)解决方案必须只有JavaScript,而不是JQuery

现在我想一想,理解这个问题的更好方法是使用

var yourDiv = document.getElementById("some-id");
    getComputedStyle(yourDiv).getPropertyValue("margin-top")

而没有CCD_ 4元件。

谢谢。

var div = document.createElement("div")
div.className = "yScrollButton" // or xScrollButton
getComputedStyle(div).getPropertyValue("min-width")

这就是你要找的吗?


编辑:也许你必须先把它添加到DOM中(由@Phil):以下是如何在不改变原始元素属性的情况下完成它。您也可以跳过hiddenDiv,并在div本身上设置display = "none"

var hiddenDiv = document.createElement("div")
hiddenDiv.style.display = "none"
document.body.appendChild(hiddenDiv)
var div = document.createElement("div")
hiddenDiv.appendChild(div)
div.className = "yScrollButton" // or xScrollButton
getComputedStyle(div).getPropertyValue("min-width")
hiddenDiv.parentNode.removeChild(hiddenDiv)

short:

var div = document.createElement("div")
div.style.display = "none"
document.body.appendChild(div)
div.className = "yScrollButton" // or xScrollButton
getComputedStyle(div).getPropertyValue("min-width")
div.parentNode.removeChild(div)

创建一个临时元素是我的做法,但(至少在我的测试中),你必须将元素插入文档(因此是display = 'none'

function getStyle() {
  var e = document.createElement('div');
  e.className = 'foo';
  e.style.display = 'none';
  document.body.appendChild(e);
  var style = window.getComputedStyle(e),
    obj = {
      'min-width': style['min-width'],
      'min-height': style['min-height']
    };
  document.getElementById('out').innerHTML = JSON.stringify(obj, null, '  ');
  document.body.removeChild(e);
}
.foo {
  min-width: 30px;
  min-height: 30px;
}
<button onclick="getStyle()" type="button">Get <code>.foo</code> style</button>
<pre id="out"></pre>