繁体   English   中英

没有源元素的JavaScript getComputedStyle?

[英]JavaScript getComputedStyle without source element?

本质上,我试图使用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; 属性值,而无需使用元素来查找它们。 通常在这种情况下,您可以使用getComputedStyle https://stackoverflow.com/a/18676007/3011082,但是在这种情况下,我无法获得计算样式的source元素(请参见下面的示例)!

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

同样,这很令人困惑,因此请告诉我您是否不理解:) 解决方案必须仅使用JavaScript,不能使用JQuery。

现在我考虑了一下,理解这个问题的更好方法是使用

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

没有yourDiv元素。

谢谢。

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)

短:

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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM