用户名:yeaon
层叠样式表(CSS照走企亮)的主要目的是给h**TML元素添加样式,然而,在一些案例中给文档添加额外的元素是多余的或是不可能的。事实上CSS中有一个特性允许我们添加额外元素而不扰乱文档本身,这就是“伪元素”。
前面的话
无法直接给befor由配历换针则概究e和after伪元素设置js效果
例子说明
现在需要来自为(id为box,内容为"我是测试内容"的div)添加(:before内容为"前缀",颜色为红色的伪问答类)
<!DOCTY
交元超地啊守会PEhtml><htmllang="en"><head> <metachar市挥有set="UTF-8"> <title>Document</title></head><b司抓ody> <d口ivid="box">我是测试内容</div> <script> varoBox=document.getElementById('box'); </script></b孔杀看入联究死ody></html>解决办样服征商列编领法
【方法一】动态嵌入CS口白时手S样式
IE8-浏览器将<s杨理概罪前青油们料英收tyle>标签当作特殊的节点,不允许访问其子节点。IE10-浏览器支持使用styleSheet.cssText属性来设置样式。兼容写法如下:
<script>functionloadStyleString(css){varstyle=document.createEle第施克切买酒千行促ment("style");style.type="text/css";try{style.appendChild(document.createTextNode(css));}catch(ex){style.styleSheet.cssText=css;}varh育投富火难ead=documen具动望预右模t.getElementsByTagName('head')[0];head.appendChild(style);}loadStyl候原eString("#box几据型日境合精那阶求误:before{co继队烟调材ntent:'前缀';color:red;}");<script>
【方法二】添加自带伪类的类名
<style>.change:before{content:"前缀";执神促取规满试又受color:red;}</style><script>oBox.className='change';</script> [缺点]此方法无法控制伪元素里面的content属性的值
【方法三】利用setAttribute实现自定义conte否口直尽密脱重代编照因nt内容
<style> .change:before{content:attr(data-beforeData);color:red;}</style><script>oBox.setAttribute('data-beforeData','前缀');</script> [注意]此方法只可用setAttribute实现,经测试用dataset方法无效
【方法四】添加样式表
firefox浏览器不支持addRule()方法,IE8-浏览器不支持insertRule()方法。兼容写法如下:
<script>functioninsertRule(sheet,ruleKey,ruleValue,index){ returnsheet.insertRule?sheet.insertRule(ruleKey+'{'+ruleValue+'}',index):sheet.addRule(ruleKey,ruleValue,index); }insertRule(document.styleSheets[0],'#box:before','content:"前缀";color:red;',0)</script>
[缺点]该方法必须有**<style>或用<link>链接外部样式,否则若不存在样式表,则document.styleSheets为空列表,则报错
【方法五】修改样式表
先使用方法四添加空的样式表,然后获取新生成的<style>并使用其innerh**TML属性来修改样式表
<script>functionloadStyleString(css){varstyle=document.createElement("style");style.type="text/css";try{style.appendChild(document.createTextNode(css));}catch(ex){style.styleSheet.cssText=css;}varhead=document.getElementsByTagName('head')[0];head.appendChild(style);}loadStyleString('');document.head.getElementsByTagName('style')[1].innerh**TML="#oBox:before{color:"+colorValue+";}";</script> [注意]只能使用getElementsByTagName('style')[1]的方法,经测验使用stylesheets[1]方法无效
DEMO
<演示框>点击下列相应属性值可进行演示