給before和after偽元素設(shè)置js效果的方法
層疊樣式表(CSS)的主要目的是給HTML元素添加樣式,然而,在一些案例中給文檔添加額外的元素是多余的或是不可能的。事實上CSS中有一個特性允許我們添加額外元素而不擾亂文檔本身,這就是“偽元素”。
前面的話
無法直接給before和after偽元素設(shè)置js效果
例子說明
現(xiàn)在需要為(id為box,內(nèi)容為"我是測試內(nèi)容"的div)添加(:before內(nèi)容為"前綴",顏色為紅色的偽類)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <div id="box">我是測試內(nèi)容</div> <script> var oBox = document.getElementById('box'); </script> </body> </html>
解決辦法
【方法一】動態(tài)嵌入CSS樣式
IE8-瀏覽器將<style>標(biāo)簽當(dāng)作特殊的節(jié)點,不允許訪問其子節(jié)點。IE10-瀏覽器支持使用styleSheet.cssText屬性來設(shè)置樣式。兼容寫法如下:
<script> function loadStyleString(css){ var style = document.createElement("style"); style.type = "text/css"; try{ style.appendChild(document.createTextNode(css)); }catch(ex){ style.styleSheet.cssText = css; } var head = document.getElementsByTagName('head')[0]; head.appendChild(style); } loadStyleString("#box:before{content:'前綴';color: red;}"); <script>
【方法二】添加自帶偽類的類名
<style> .change:before{content: "前綴";color: red;} </style> <script> oBox.className = 'change'; </script>
[缺點]此方法無法控制偽元素里面的content屬性的值
【方法三】利用setAttribute實現(xiàn)自定義content內(nèi)容
<style> .change:before{content: attr(data-beforeData);color: red;} </style> <script> oBox.setAttribute('data-beforeData','前綴'); </script>
[注意]此方法只可用setAttribute實現(xiàn),經(jīng)測試用dataset方法無效
【方法四】添加樣式表
firefox瀏覽器不支持addRule()方法,IE8-瀏覽器不支持insertRule()方法。兼容寫法如下:
<script> function insertRule(sheet,ruleKey,ruleValue,index){ return sheet.insertRule ? sheet.insertRule(ruleKey+ '{' + ruleValue + '}',index) : sheet.addRule(ruleKey,ruleValue,index); } insertRule(document.styleSheets[0],'#box:before','content:"前綴";color: red;',0) </script>
[缺點]該方法必須有內(nèi)部<style>或用<link>鏈接外部樣式,否則若不存在樣式表,則document.styleSheets為空列表,則報錯
【方法五】修改樣式表
先使用方法四添加空的樣式表,然后獲取新生成的<style>并使用其innerHTML屬性來修改樣式表
<script> function loadStyleString(css){ var style = document.createElement("style"); style.type = "text/css"; try{ style.appendChild(document.createTextNode(css)); }catch(ex){ style.styleSheet.cssText = css; } var head = document.getElementsByTagName('head')[0]; head.appendChild(style); } loadStyleString(''); document.head.getElementsByTagName('style')[1].innerHTML = "#oBox:before{color: " + colorValue + ";}"; </script>
[注意]只能使用getElementsByTagName('style')[1]的方法,經(jīng)測驗使用stylesheets[1]方法無效
DEMO
<演示框>點擊下列相應(yīng)屬性值可進(jìn)行演示
相關(guān)文章
Layui數(shù)據(jù)表格判斷編輯輸入的值,是否為我需要的類型詳解
今天小編就為大家分享一篇Layui數(shù)據(jù)表格判斷編輯輸入的值,是否為我需要的類型詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-10-10javascript設(shè)置頁面背景色及背景圖片的方法
這篇文章主要介紹了javascript設(shè)置頁面背景色及背景圖片的方法,涉及JavaScript動態(tài)操作頁面元素屬性的相關(guān)技巧,需要的朋友可以參考下2015-12-12ES6模塊化的import和export用法方法總結(jié)
這篇文章主要介紹了ES6模塊化的import和export用法方法總結(jié),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-08-08