由于IE8不支持getComputedStyle,我们只能使用currentStyle.但是,它不会返回某些属性的实际"计算"值.
例如:
<style type="text/css">
#div {/* no properties are defined here */}
</style>
Run Code Online (Sandbox Code Playgroud)
<div id="div">div</div>
Run Code Online (Sandbox Code Playgroud)
// returns "medium" instead of 0px
document.getElementById('div').currentStyle.borderLeftWidth
// returns "auto" instead of 0px
document.getElementById('div').currentStyle.marginLeft
// returns "undefined" instead of 1
document.getElementById('div').currentStyle.opacity
Run Code Online (Sandbox Code Playgroud)
有没有人在不使用jQuery或其他Javascript库的情况下为所有属性提供跨浏览器解决方案?
我在JavaScript插件中找到了这个getComputedStyle polyfill
if (!computed) {
window.getComputedStyle = function(el) {
this.el = el;
this.getPropertyValue = function(prop) {
var re = /(\-([a-z]){1})/g;
if (prop === "float") {
prop = "styleFloat";
}
if (re.test(prop)) {
prop = prop.replace(re, function () {
return arguments[2].toUpperCase();
});
}
return el.currentStyle[prop] ? el.currentStyle[prop] : null;
};
return this;
};
}
Run Code Online (Sandbox Code Playgroud)
getcomputedstyle()是否有任何jQuery等价物;
我需要得到margin-top一个input使用JavaScript.这是jQuery代码,它工作正常:
alert($("#input").css('margin-top'))
Run Code Online (Sandbox Code Playgroud)
但我需要它在纯Javascript中,我尝试了以下代码没有运气
alert(document.getElementById('input').style.marginTop)
Run Code Online (Sandbox Code Playgroud)
如何使它在纯JavaScript中运行?