CSS样式的 读取&设置

356 阅读1分钟

样式读取

内联样式

    ele.style.styleName
    ele.style[style-name]

    //只能读内联样式,不能读样式表中的样式

读取当前生效样式

  • IE浏览器
    ele.currentStyle.styleName
  • 一般浏览器
    Window.getComputedStyle(box1 , null)[width]

    // 参数1:要获取样式的元素
    // 参数2:要获取元素的伪类,不需要时可以传入null;
  • 自定义IE浏览器和一般浏览器读取元素的兼容方式:
    function getStyle(obj , name){
        if(window.getComputedStyle){
            return getComputedStyle(obj,null)[name];
        }else{
            return obj.currentStyle[name];
        }
    }
    
    // 简写:
    return window.getComputedStyle?getComputedStyle(obj,null)[name]:obj.currentStyle[name];

样式设置

1. style

    ele.style.fontSize = '24px';
    ele.style[font-size] = '24px';

2. setAttribute

    ele.setAttribute('height', 100);
    ele.setAttribute('height', '100px');

3. setAttribute/style

    element.setAttribute('style', 'height: 100px !important');

4. style.setProperty

    element.style.setProperty('height', '300px', 'important');

5. 改变class

    element.className = 'warn';
    element.className += 'warn warn-border';

6. cssText

    element.style.cssText = 'height: 100px !important';
    element.style.cssText += 'height: 100px !important';

7. 引入新的css样式文件

    function addNewStyle(newStyle) {
    var styleElement = document.getElementById('styles_js');
        if (!styleElement) {
            styleElement = document.createElement('style');
            styleElement.type = 'text/css';
            styleElement.id = 'styles_js';
            document.getElementsByTagName('head')[0].appendChild(styleElement);
        }
        
        styleElement.appendChild(document.createTextNode(newStyle));
    }

    addNewStyle('.box {height: 100px !important;}');

8. 使用addRule、insertRule

    // 在原有样式操作
    document.styleSheets[0].addRule('.box', 'height: 100px');
    document.styleSheets[0].insertRule('.box {height: 100px}', 0);

    // 或者插入新样式时操作
    var styleEl = document.createElement('style'),
        styleSheet = styleEl.sheet;

    styleSheet.addRule('.box', 'height: 100px');
    styleSheet.insertRule('.box {height: 100px}', 0);

    document.head.appendChild(styleEl);

内容参考其他帖子加上自己整合