如何将JavaScript设置样式属性返回到CSS默认值 [英] How to return a javascript set style property to CSS default

查看:219
本文介绍了如何将JavaScript设置样式属性返回到CSS默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我试图解决如何使用javascript更改样式属性后,我可以恢复到样式表中的值(包括单位)。下面的例子,我想输出读取 100px (CSS中的值),而不是 10px getComputedStyle 给出。



我还将虚拟div保留在 25px ,因此删除 style 属性将无效。



有克隆节点和读取高度和存储在属性(http://jsfiddle.net/daneastwell/zHMvh/4/),但这不是真的得到浏览器的默认css值(特别是如果这是设置在 em s)。



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; 


I'm trying to work out how, after changing style properties with javascript, I can revert to the value in the stylesheet (including the units).

In the example below, I'd like the output to read 100px (the value in the CSS), rather than 10px, as getComputedStyle gives.

I'd also keep the dummy div at top:25px, so removing the style property won't work.

The best I have is cloning the node and reading the height and storing in a property (http://jsfiddle.net/daneastwell/zHMvh/4/), but this is not really getting the browser's default css value (especially if this is set in ems).

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>

解决方案

Just clear the inline style you wish to fallback to original stylesheet on.

elem.style.left = null;

这篇关于如何将JavaScript设置样式属性返回到CSS默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆