[Toc]
通過新創(chuàng)建<link>
元素船庇,賦值其src
屬性來(lái)達(dá)到動(dòng)態(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)
}
通過設(shè)置樣式文本為<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中是無(wú)法運(yùn)行的喉誊。另外IE10運(yùn)行的話需要修改let為var顶瞳。
解決IE創(chuàng)建動(dòng)態(tài)樣式失敗
IE8以及以下元素需要訪問styleSheet屬性徘郭,再通過這個(gè)屬性下的cssText屬性來(lái)添加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)
封裝一個(gè)跨瀏覽器的樣式寫入函數(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