DOM編程——動態(tài)樣式

[Toc]

通過新創(chuàng)建<link>元素,賦值其src屬性來達到動態(tài)插入樣式的目的

        let oLink = document.createElement('link')
        oLink.rel = 'stylesheet'
        oLink.type = 'text/css'
        oLink.href = url
        let oHead = document.head // html5新增的屬性,指向文檔<head>元素
        oHead.appendChild(oLink)

封裝以上代碼

        function loadStyles(url) {
            let oLink = document.createElement('link')
            oLink.rel = 'stylesheet'
            oLink.type = 'text/css'
            oLink.href = url
            let oHead = document.head
            oHead.appendChild(oLink)
        }

通過設置樣式文本為<style>元素創(chuàng)建樣式

        let oStyle = document.createElement('style')
        oStyle.type = "text/css"
        oStyle.appendChild(document.createTextNode("div{width:200px;height:200px;background-color:#456;}"))
        let oHead = document.head
        oHead.appendChild(oStyle)
  • 上面的代碼在IE8以及以下版本IE中是無法運行的。另外IE10運行的話需要修改let為var。

解決IE創(chuàng)建動態(tài)樣式失敗

  • IE8以及以下元素需要訪問styleSheet屬性,再通過這個屬性下的cssText屬性來添加css代碼

  •         var oStyle = document.createElement('style')
            oStyle.type = "text/css"
            try {
                oStyle.appendChild(document.createTextNode("div{width:200px;height:200px;background-color:#456;}"))
            } catch (ex) {
                oStyle.styleSheet.cssText = "div{width:200px;height:200px;background-color:#456;}"
            }
            var oHead = document.getElementsByTagName('head')[0]  // IE8不支持document.head
            oHead.appendChild(oStyle)
    

封裝一個跨瀏覽器的樣式寫入函數(shù)

        function loadStyleString(styleStr) {
            var oStyle = document.createElement('style')
            oStyle.type = "text/css"
            var oHead = null
            try {
                oHead = document.head
                oStyle.appendChild(document.createTextNode(styleStr))
            } catch (ex) {
                oHead = document.getElementsByTagName('head')[0]
                oStyle.styleSheet.cssText = styleStr
            }
            oHead.appendChild(oStyle)
        }

        var cssText = 'div{width:200px;height:200px;background-color:#789;}'
        loadStyleString(cssText)

10.17

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容