代码改变世界

javascript 获取元素计算后的样式及删除style中指定的样式属性

2011-07-16 13:17  飞魚  阅读(1633)  评论(0编辑  收藏  举报
<style>
        #mytest
        {
            width: 100px;
            height: 100px;
            border: 1px solid blue;
        }
</style>
<div id="mytest" style="color: red; border: 1px solid red;"></div>
<script type="text/javascript">// <![CDATA[
    var div = document.getElementById("mytest");

    var currentStyle = null;
    try {
        //获取不到综合属性的值,如border,想获取要拆分
        currentStyle = document.defaultView.getComputedStyle(div, null);
    } catch (e) {
        currentStyle = div.currentStyle; //兼容IE
    }

    alert(currentStyle.width); //100px

    try {
        div.style.removeProperty("border");
    } catch (e) {
       //IE下删除,不包括IE9 
       div.style.cssText = div.style.cssText.replace(/(border[^;]+;)|(border[^;]+)/ig, "");
    }

    alert(div.style.cssText); //color:red;
// ]]></script>