querySelector为什么不能获取伪元素

首先我们需要了解什么是伪元素
常见的伪元素有::after和::brfore,他们用于在CSS渲染中向元素的头或者尾插入内容,其不影响文档本身,只会影响最终的样式。
也即是说,这些伪元素不会出现在DOM中,仅仅在CSS渲染层中。
我们使用Window..querySelector(“:before”)其实操作的是DOM元素,因为伪元素不存在DOM中,所以无法操作伪元素。
伪元素的写法:
在CSS3中,建议伪元素使用两个冒号(::)语法,目的是为了区分伪类和伪元素。大多数浏览器都支持这两种表示语法。只有 ::selection 永远只能以两个冒号开头(::)。因为IE8只支持单冒号的语法,所以,如果你想兼容IE8,保险的做法是使用单冒号。
如何获取伪类元素及其属性值?
语法:window.getComputedStyle(element[, pseudoElement])
示例如下:

var myElement = document.getElementById("my");//获取DOM中id为my的元素
var beforeStyle = window.getComputedStyle(myElement, ":before");//获取伪元素的CSS样式声明对象
console.log(beforeStyle.color); // red 键值访问 属性值需要驼峰命名 backgroundColor
console.log(beforeStyle.getPropertyValue("color"));//red IE9+都支持 在IE6~8中,使用getAttribute()来代替

如何更改伪类元素的样式?
1.直接更改class

// CSS代码
.red::before { 
    content: "red"; 
    color: red; 
}
.green::before { 
    content: "green"; 
    color: green;
} 
// HTML代码
<div class="red">内容内容内容内容</div>

2.使用CSSStyleSheet的insertRule来为伪元素修改样式

document.styleSheets[0].addRule('.red::before','color: green'); // 支持IE 
document.styleSheets[0].insertRule('.red::before { color: green }', 0); // 支持非IE的现代浏览器

如何修改伪元素的content的属性值?
1.使用CSSStyleSheet的insertRule来为伪元素修改样式

var latestContent = "修改过的内容";
var red=document.querySelector('.red')
var formerContent = window.getComputedStyle(red, '::before').getPropertyValue('content');
document.styleSheets[0].addRule('.red::before','content: "' + latestContent + '"'); // 支持IE
document.styleSheets[0].insertRule('.red::before { content: "' + latestContent + '" }', 0);// 支持非IE的现代浏览器

2.使用DOM元素的data-*属性来更改content的值

// CSS代码
.red::before {
    content: attr(data-attr);
    color: red;
}

// HTML代码
<div class="red" data-attr="red">内容内容内容内容</div>

// JacaScript代码
var red=document.querySelector('.red')
red.setAttribute('data-attr', '26546545');
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务