CSS Query不能通过$(":before")
、$(dom).find(":before")
、document.querySelector(“:before”)来获取:before为元素
为什么不能直接用JS获取伪元素呢?
::before ::after,用于在CSS渲染中向元素是的头部或尾部插入内容,它们不受文档约束,也不影响文档本身,只影响最终样式。这些添加的内容不会出现在DOM中,仅仅是在CSS渲染层中加入
伪元素可以被浏览器渲染,但本身并不是DOM元素。它不存在于文档中,所以JS无法直接操作它
而jQuery的选择器都是基于DOM元素的,因此也并不能直接操作伪元素
- ::after
- ::before
- ::first-line
- ::first-letter
- ::selection
- ::backdrop
最常用的是::after和::before
具体介绍->https://www.jianshu.com/p/2deb84ad22c8
CSS3中,建议为元素使用两个冒号(::语法),而不是一个冒号(,目的是为了区分伪类和伪元素。大多数浏览器都支持着两种表示语法。
只有::selection永远只能以两个冒号开头(:
因为IE8只支持单冒号的语法,所以,如果想兼容IE8,保险的做法是使用单冒号
window.getComputedStyle()
获取伪元素的CSS样式声明对象。然后利用getPropertyValue
方法或直接使用键值访问都可以获取对应的属性值
语法:window.getComputedStyle(element[, pseudoElement])
- 参数如下:
- element(Object):伪元素的所在的DOM元素;
- pseudoElement(String):伪元素类型。可选值有:”:after”、”:before”、”:first-line”、”:first-letter”、”:selection”、”:backdrop”;
- 对于float属性,如果使用键值访问,不能直接使用getComputedStyle(element,null).float,而应该是cssFloat与styleFloat
- 直接使用键值访问,则属性的键需要使用驼峰写法,如:style.backgroundColor
- 使用getPropertyValue()方法未必可以驼峰书写形式(不支持驼峰写法),例如:style.getPropertyValue(“border-top-color”);
- getPropertyValue()方法在IE9+和其他现代浏览器中都支持;在IE6~8中,可以使用getAttribute()方法来代替
// CSS代码
.red::before {
content: "red";
color: red;
}
.green::before {
content: "green";
color: green;
}
// HTML代码
<div class="red">内容内容内容内容</div>
// jQuery代码
$(".red").removeClass('red').addClass('green');
document.styleSheet[0].addRule('.red::before','color:green');//支持IE document.styleSheets
var style=document.createElement("style");
document.head.appendChild(style);
sheet=style.sheet;
sheet.addRule('.red::before','color:green');//兼容IE浏览器
sheet.insertRule('.red::before{color:green}')//支持非IE的现代浏览器
或使用jQuery
$('').appendTo('heda');
var latestContent="修改过的内容";
var formerContent=window.getComputedStyle($('.red'),'::before').getPropertyValue('content');
document.styleSheets[0].addRule('.red::before','content:"'+latestContent+'"');
ducument.styleSheets[0].insertRule('.red::before{content:"'+latestContent +'"}',0);
//CSS代码
.red::before{
content:attr(data-attr);
color:red;
}
//HTML
<div class="red" data-attr="red">内容内容</div>
//JavaScript代码
$('.red').attr('data-attr','green');
$('.red').attr('data-attr','green);