日期:2014-05-16  浏览次数:20493 次

js 动态添加和删除样式
可以加一个id 或者 直接给个style 我是这样写的setAttribute("style","outline:"+color+" dashed 2px;") 但不知道要怎么 点击按钮时把样式删除。

------解决方案--------------------
HTML code

<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="gb2312" />
        <title></title>
    </head>
    <body>
        <div id="test" style="border:1px solid red; color:red; font-size:123px;">123</div>
        <button id="btn">click</button>
        <script>
            function $(el){
                return typeof el == 'string' ? document.getElementById(el) : el;
            }
            function removeStyle(obj, name){
                if(!name) {
                    obj.removeAttribute('style');
                    return obj;
                }
                var s = obj.style;
                if(s.removeAttribute){
                    s.removeAttribute(name);
                } else {
                    name = name.replace(/([A-Z])/g, function(v){
                        return '-' + v.toLowerCase();
                    });
                    s.removeProperty(name);
                }
                return obj;
            }
            
            $('btn').onclick = function(){
               removeStyle($('test'), 'fontSize')
            }
        </script>
    </body>
</html>