有一个带.bg类的元素。 css规则如下:
.bg {
width:100%;
}
.bg:before {
position: absolute;
content: '';
background: rgba(0,0,0,0.5);
width: 100%;
height: 100%;
}
我有一个javascript规则,我将高度设置为bg类:
$(".bg").height($(document).height());
但我想将$(document).height()设置为.bg:before。我怎样才能通过javascript实现这一目标?
因为$(".bg:before").height($(document).height());
不起作用。
提前致谢
答案 0 :(得分:1)
使用JavaScript,您可以通过这种方式修改.bg:before
的规则。
循环遍历样式表中的规则,如果当前规则为.bg:before
(r.selectorText == .bg:before
),请更改其height
(r.style.height = window.innerHeight + 'px'
)。
var ss = document.styleSheets;
for (i = 0; i < ss.length; i++) {
var rules = ss[i];
for (j = 0; j < rules.cssRules.length; j++) {
var r = rules.cssRules[j];
if (r.selectorText == ".bg:before" || r.selectorText == ".bg::before") {
console.log('Old rule: ' + r.cssText)
r.style.height = window.innerHeight + 'px';
console.log('Modified rule: ' + r.cssText)
}
}
}
&#13;
.bg {
width: 100%;
}
.bg::before {
position: absolute;
content: '';
background: rgba(0, 0, 0, 0.5);
width: 100%;
height: 100%;
}
&#13;
答案 1 :(得分:0)
你根本无法使用javascript,因为伪元素不是DOM的一部分。