首页 > Web开发 > 详细

深入理解脚本化CSS系列第五篇——动态样式

时间:2016-09-07 22:42:24      阅读:165      评论:0      收藏:0      [点我收藏+]

前面的话

  很多时候,DOM操作比较简单明了,因此用javascript生成那些通常原本是HTML代码生成的内容并不麻烦。但由于浏览器充斥着隐藏的陷阱和不兼容问题,处理DOM中的某些部分时要复杂一些,比如动态样式就相对较复杂

  所谓动态样式,是指在页面加载时并不存在,在页面加载完成后动态添加到页面的样式

  动态样式包括两种情况:一种是通过<link>元素插入外部样式表,另一种是通过<style>元素插入内部样式。下面将详细介绍这两种情况

 

外部样式

/*style.css里面的内容*/
.box{height:100px;width:100px;background-color: pink;}
var link = document.createElement("link");
link.rel = "stylesheet";
link.type = "text/css";
link.href = "style.css";
var head = document.getElementsByTagName(‘head‘)[0];
head.appendChild(link);

  使用函数封装如下:

<div class="box">测试文字</div>
<button id="btn">动态添加样式</button>
<script>
function loadStyles(url){
    loadStyles.mark = ‘load‘;
    var link = document.createElement("link");
    link.rel = "stylesheet";
    link.type = "text/css";
    link.href = url;
    var head = document.getElementsByTagName(‘head‘)[0];
    head.appendChild(link); 
}
btn.onclick = function(){
    if(loadStyles.mark != ‘load‘){
        loadStyles("style.css");        
    }
}
</script>

内部样式

var style = document.createElement("style");
style.type = "text/css";
style.innerHTML = ".box{height:100px;width:100px;background-color: pink;}";
var head = document.getElementsByTagName(‘head‘)[0];
head.appendChild(style); 

  使用函数封装如下:

<div class="box">测试文字</div>
<button id="btn">动态添加样式</button>
<script>
function loadStyles(str){
    loadStyles.mark = ‘load‘;
    var style = document.createElement("style");
    style.type = "text/css";
    style.innerHTML = str;
    var head = document.getElementsByTagName(‘head‘)[0];
    head.appendChild(style); 
}
btn.onclick = function(){
    if(loadStyles.mark != ‘load‘){
        loadStyles(".box{height:100px;width:100px;background-color: pink;}");        
    }
}
</script>

  [注意]该方法在IE8-浏览器中报错,因为IE8-浏览器将<style>视为当作特殊的节点,不允许访问其子节点或设置innerHTML属性

兼容

  IE浏览器支持访问并修改元素的CSSStyleSheet对象的cssText属性,通过修改该属性可实现类似效果

<div class="box">测试文字</div>
<button id="btn">动态添加样式</button>
<script>
function loadStyles(str){
    loadStyles.mark = ‘load‘;
    var style = document.createElement("style");
    style.type = "text/css";
    try{
        style.innerHTML = str;
    }catch(ex){
        style.styleSheet.cssText = str;
    }
    var head = document.getElementsByTagName(‘head‘)[0];
    head.appendChild(style); 
}
btn.onclick = function(){
    if(loadStyles.mark != ‘load‘){
        loadStyles(".box{height:100px;width:100px;background-color: pink;}");        
    }
}
</script>    

 

深入理解脚本化CSS系列第五篇——动态样式

原文:http://www.cnblogs.com/xiaohuochai/p/5851203.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!