• 用javascript插入<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");
        var 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");
        var 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”);
    

      

  • 相关阅读:
    Mysql-函数coalesce-查询为空设置默认值
    js-定时任务setInterval,setTimeout,clearInterval,clearTimeout
    Json-转换
    Hibernate-Criteria用法
    Js-字符转换数字
    Mysql-日期转换
    Freemarker-数字默认格式化问题
    Freemarker-标签使用
    算法-毛利率
    Hibernate-org.hibernate.QueryException: could not resolve property: code of:
  • 原文地址:https://www.cnblogs.com/jkr666666/p/11285793.html
Copyright © 2020-2023  润新知