我正在尝试弄清楚在使用javascript更改样式属性后,我可以恢复到样式表中的值(包括单位)。
在下面的示例中,我希望输出读取100px
(CSS中的值),而不是10px
,如getComputedStyle
所示。
我还将虚拟div保留在top:25px
,因此删除style
属性将无效。
我所拥有的最好的是克隆节点并读取高度并存储在属性(http://jsfiddle.net/daneastwell/zHMvh/4/)中,但这并没有真正获得浏览器的默认css值(特别是如果在{{1}中设置的话) } S)。
http://jsfiddle.net/daneastwell/zHMvh/1/
em
答案 0 :(得分:22)
只需清除您希望回退到原始样式表的内联样式。
elem.style.left = null;
答案 1 :(得分:5)
style object有一个内置的removeProperty()
方法,所以你可以这样做:
elem.style.removeProperty('left');
据我所知,这与将null
设置为{{1}}的效果完全相同,为abaelter suggested。我认为为了完整起见可能值得包括。
答案 2 :(得分:1)
结合abaelter的答案和http://robertnyman.com/2006/04/24/get-the-rendered-style-of-an-element/给出了以下功能:
var getCssStyle = function(elementId, cssProperty) {
var elem = document.getElementById(elementId);
var inlineCssValue = elem.style[cssProperty];
// If the inline style exists remove it, so we have access to the original CSS
if (inlineCssValue !== "") {
elem.style[cssProperty] = null;
}
var cssValue = "";
// For most browsers
if (document.defaultView && document.defaultView.getComputedStyle) {
cssValue = document.defaultView.getComputedStyle(elem, "").getPropertyValue(cssProperty);
}
// For IE except 5
else if (elem.currentStyle){
cssProperty = cssProperty.replace(/\-(\w)/g, function (strMatch, p1) {
return p1.toUpperCase();
});
cssValue = elem.currentStyle[cssProperty];
}
// Put the inline style back if it had one originally
if (inlineCssValue !== "") {
elem.style[cssProperty] = inlineCssValue;
}
return cssValue;
}
放入示例代码并进行测试:
console.log("getCssStyle: " + getCssStyle("elem-container", "left"));
让我们getCssStyle: 100px
允许您查看原始CSS值。如果你只想恢复该值,那么就像abaelter所说的那样,并null
要恢复的CSS值。