Javascript 获取样式';s属性
我有一个关于通过javascript获取DOM样式的问题Javascript 获取样式';s属性,javascript,css,Javascript,Css,我有一个关于通过javascript获取DOM样式的问题 #quicklink { position: absolute; top: 500px; left: 500px; } <div id="quicklink" class="draggable"> <img class="menu_icon" src="4a.png" src="" /> </div> 谢谢大家! 试试这个 fun
#quicklink {
position: absolute;
top: 500px;
left: 500px;
}
<div id="quicklink" class="draggable">
<img class="menu_icon" src="4a.png" src="" />
</div>
谢谢大家! 试试这个
function getCssProperty(elmId, property){
var elem = document.getElementById(elmId);
return window.getComputedStyle(elem,null).getPropertyValue(property);
}
// You could now get your value like
var top = getCssProperty("quicklink", "top");
console.log(top)
这是因为样式没有作为该元素ID上的属性驻留在DOM中。您可以尝试
getComputeStyle()
访问通过单独CSS应用的样式
var elem1 = document.getElementById("elemId");
var style = window.getComputedStyle(elem1, null);
MDN:
W3C:试试这个:
var element = document.getElementById('quicklink'),
style = window.getComputedStyle(element),
top = style.getPropertyValue('top');
你能解释一下为什么它总是用空字符串值记录吗?文档解释了
getComputedStyle()
在应用活动样式表并解析这些值可能包含的任何基本计算之后,给出了元素的所有CSS属性的值。因此,这可能是直到那时才应用活动样式表的空字符串的原因。你能解释一下为什么它总是用空字符串值记录吗?
var element = document.getElementById('quicklink'),
style = window.getComputedStyle(element),
top = style.getPropertyValue('top');