我试图弄清楚如何使用javascript更改样式属性后,我可以还原为样式表(包括单位)中的值。如何将javascript设置样式属性返回到CSS默认
在下面的示例中,我希望输出为100px
(CSS中的值),而不是10px
,如getComputedStyle
所示。
我也会保留在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>
为什么你不能使用CSS类?然后,您只需添加/删除它们而不是更改个别样式属性。 –
此外,实际上left_is_10px的当前值是因为getComputerStyle返回该元素的计算样式(包括style属性),而不仅仅是CSS中指定的规则。注意:请注意,旧版本的IE不支持getComputedStyle。 –
我正在执行调整任务的任务,因此计算'左'值,所以班级不会帮助,对不起,没有更具体。 –