sta*_*tan 60 html javascript css stylesheet
我正在寻找一种方法来从样式标签上设置样式的元素中检索样式.
<style>
#box {width: 100px;}
</style>
Run Code Online (Sandbox Code Playgroud)
在身体里
<div id="box"></div>
Run Code Online (Sandbox Code Playgroud)
我正在寻找没有使用库的直接javascript.
我尝试了以下方法,但继续收到空白:
alert (document.getElementById("box").style.width);
alert (document.getElementById("box").style.getPropertyValue("width"));
Run Code Online (Sandbox Code Playgroud)
我注意到,如果我使用javascript设置样式,但我无法使用上述样式,但无法使用样式标记.
CMS*_*CMS 78
该element.style
属性仅让您知道在该元素中定义为内联的CSS属性(以编程方式或在元素的style属性中定义),您应该获得计算出的样式.
以跨浏览器的方式做起来并不是那么容易,IE有自己的方式,通过element.currentStyle
属性,以及DOM Level 2 标准方式,由其他浏览器实现的是通过该document.defaultView.getComputedStyle
方法.
这两种方法有差异,例如,在IE element.currentStyle
属性期待您访问的两个或多个单词组成的CCS属性名驼峰(例如maxHeight
,fontSize
,backgroundColor
等),标准的方式希望用破折号分隔的字词的属性(如max-height
,font-size
,background-color
,等等).
此外,IE element.currentStyle
将返回指定单位中的所有大小(例如12pt,50%,5em),标准方式将始终以像素为单位计算实际大小.
我前段时间做了一个跨浏览器的功能,它允许你以跨浏览器的方式获取计算出的样式:
function getStyle(el, styleProp) {
var value, defaultView = (el.ownerDocument || document).defaultView;
// W3C standard way:
if (defaultView && defaultView.getComputedStyle) {
// sanitize property name to css notation
// (hypen separated words eg. font-Size)
styleProp = styleProp.replace(/([A-Z])/g, "-$1").toLowerCase();
return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp);
} else if (el.currentStyle) { // IE
// sanitize property name to camelCase
styleProp = styleProp.replace(/\-(\w)/g, function(str, letter) {
return letter.toUpperCase();
});
value = el.currentStyle[styleProp];
// convert other units to pixels on IE
if (/^\d+(em|pt|%|ex)?$/i.test(value)) {
return (function(value) {
var oldLeft = el.style.left, oldRsLeft = el.runtimeStyle.left;
el.runtimeStyle.left = el.currentStyle.left;
el.style.left = value || 0;
value = el.style.pixelLeft + "px";
el.style.left = oldLeft;
el.runtimeStyle.left = oldRsLeft;
return value;
})(value);
}
return value;
}
}
Run Code Online (Sandbox Code Playgroud)
对于某些情况,上述函数并不完美,例如对于颜色,标准方法将以rgb(...)表示法返回颜色,在IE上,它们将在定义时返回它们.
我目前正在撰写该主题的一篇文章,您可以在此处跟踪我对此功能所做的更改.
jus*_*_de 19
我相信你现在能够使用Window.getComputedStyle()
var style = window.getComputedStyle(element[, pseudoElt]);
Run Code Online (Sandbox Code Playgroud)
获取元素宽度的示例:
window.getComputedStyle(document.querySelector('#mainbar')).width
Run Code Online (Sandbox Code Playgroud)