zoukankan      html  css  js  c++  java
  • 用javascript插入样式

    一、用javascript插入<style>样式

    有时候我们需要利用js来动态生成页面上style标签中的css代码,方法很直接,就是直接创建一个style元素,然后设置style元素里面的css代码,最后把它插入到head元素中。

    但有些兼容性问题我们需要解决。首先在符合w3c标准的浏览器中我们只需要把要插入的css代码作为一个文本节点插入到style元素中即可,而在IE中则需要利用style元素的styleSheet.cssText来解决。

    还需要注意的就是在有些版本IE中一个页面上style标签数量是有限制的,如果超过了会报错,需要考虑这点。

    function addCSS(cssText){
        var style = document.createElement('style'),  //创建一个style元素
            head = document.head || document.getElementsByTagName('head')[0]; //获取head元素
        style.type = 'text/css'; //这里必须显示设置style元素的type属性为text/css,否则在ie中不起作用
        if(style.styleSheet){ //IE
            var func = function(){
                try{ //防止IE中stylesheet数量超过限制而发生错误
                    style.styleSheet.cssText = cssText;
                }catch(e){
    
                }
            }
            //如果当前styleSheet还不能用,则放到异步中则行
            if(style.styleSheet.disabled){
                setTimeout(func,10);
            }else{
                func();
            }
        }else{ //w3c
            //w3c浏览器中只要创建文本节点插入到style元素中就行了
            var textNode = document.createTextNode(cssText);
            style.appendChild(textNode);
        }
        head.appendChild(style); //把创建的style元素插入到head中    
    }
    
    //使用
    addCSS('#demo{ height: 30px; background:#f00;}');

    当然这只是一个最基本的演示方法,实际运用中还需进行完善,比如把每次生成的css代码都插入到一个style元素中,这样在IE中就不会发生stylesheet数量超出限制的错误了。

    封装:

    var importStyle=function importStyle(b){var a=document.createElement("style"),c=document;c.getElementsByTagName("head")[0].appendChild(a);if(a.styleSheet){a.styleSheet.cssText=b}else{a.appendChild(c.createTextNode(b))}};
    importStyle('h1 { background: red; }');//调用

    seajs封装

    seajs.importStyle=function importStyle(b){var a=document.createElement("style"),c=document;c.getElementsByTagName("head")[0].appendChild(a);if(a.styleSheet){a.styleSheet.cssText=b}else{a.appendChild(c.createTextNode(b))}};

    二、javascript插入<link>样式

    在<head>中使用<link>标签引入一个外部样式文件,这个比较简单,各个主流浏览器也不存在兼容性问题:

    function includeLinkStyle(url) {
    var link = document.createElement(“link”);
    link.rel = “stylesheet”;
    link.type = “text/css”;
    link.href = url;
    document.getElementsByTagName(“head”)[0].appendChild(link);
    }
    
    includeLinkStyle(“http://css.xxx.com/home/css/reset.css?v=20101227”);

    参考:

    http://www.cnblogs.com/2050/p/4029656.html

    本文作者starof,因知识本身在变化,作者也在不断学习成长,文章内容也不定时更新,为避免误导读者,方便追根溯源,请诸位转载注明出处:http://www.cnblogs.com/starof/p/5274781.html有问题欢迎与我讨论,共同进步。

  • 相关阅读:
    谦谦君子 温润如玉
    [Linux: vim]vim自动生成html代码
    /boot/grub/grub.conf 内容诠释
    mini_httpd在RedHat 5下安装
    html 简单学习
    v4l
    手机处理器哪个好 智能手机处理器进化知识
    小败局】一位草根北漂创业者自述:赚钱的快餐店之死
    读书
    手游研发CJ抱大腿指南
  • 原文地址:https://www.cnblogs.com/starof/p/5274781.html
Copyright © 2011-2022 走看看