我正在尝试找出如何在使用 javascript 更改样式属性后恢复为样式表中的值(包括单位)。
在下面的示例中,我希望输出为 100px
(CSS 中的值),而不是 10px
, 作为 getComputedStyle
给。
我还会将虚拟 div 保留在 top:25px
, 所以删除 style
属性将不起作用。
我最好的方法是克隆节点并读取高度并将其存储在属性(http://jsfiddle.net/daneastwell/zHMvh/4/)中,但这并不是真正获取浏览器的默认 css 值(尤其是在 em
中设置的情况下)。
http://jsfiddle.net/daneastwell/zHMvh/1/
<style>
#elem-container{
position: absolute;
left: 100px;
top: 200px;
height: 100px;
}
</style>
<div id="elem-container">dummy</div>
<div id="output"></div>
<script>
function getTheStyle(){
var elem = document.getElementById("elem-container");
elem.style.left = "10px";
elem.style.top = "25px";
var theCSSprop = window.getComputedStyle(elem,null).getPropertyValue("left");
document.getElementById("output").innerHTML = theCSSprop;
}
getTheStyle();
</script>
最佳答案
只需清除您希望回退到原始样式表的内联样式。
elem.style.left = null;
关于javascript - 如何将 javascript 设置样式属性返回到 CSS 默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10698942/