gpt4 book ai didi

javascript - 如何使用::在使用 javascript 选择器之前为元素设置高度?

转载 作者:太空宇宙 更新时间:2023-11-04 12:34:55 25 4
gpt4 key购买 nike

有一个带有 .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()); 不起作用。

提前致谢

最佳答案

使用 JavaScript,您可以用这种方式修改 .bg:before 的规则。

循环样式表中的规则,如果当前规则是.bg:before(r.selectorText == .bg:before) ,改变它的高度(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)
}
}
}
.bg {
width: 100%;
}
.bg::before {
position: absolute;
content: '';
background: rgba(0, 0, 0, 0.5);
width: 100%;
height: 100%;
}

关于javascript - 如何使用::在使用 javascript 选择器之前为元素设置高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27358143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com