`

Js动态添加样式

阅读更多
<script type="text/javascript">
//添加页面样式
function addStyle(content)
{
    var style;
    if(document.all)    //IE
    {
        style = document.createStyleSheet();
        style.cssText = content;
    }
    else
    {
        style = document.createElement("style"); 
        style.type = "text/css"; 
        //style.innerHTML = content;//Safari、Chrome 下innerHTML只读
        style.textContent = content;
    }
    try{document.getElementsByTagName("head")[0].appendChild(style);}catch(e){}//IE Error:不支持此接口
}
//添加外部样式
function includeStyle(url)
{
    var style = document.createElement("link");
    style.type = "text/css";
    style.setAttribute("rel","stylesheet");
    style.setAttribute("href",url);
    document.getElementsByTagName("head")[0].appendChild(style);
}
addStyle("#div1{background-color:#CC99FF;width:200px;height:100px;}");
includeStyle("http://www.mzwu.com/style/global.css");
</script>

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics