有一个. bg类的元素,css规则如下:
.bg {
width:100%;
}
.bg:before {
position: absolute;
content: '';
background: rgba(0,0,0,0.5);
width: 100%;
height: 100%;
}
我有一个javascript规则,我把高度设置为bg class:
$(".bg").height($(document).height());
但是我想把$(document). height()设为. bg:before,用javascript怎么实现呢?因为$(".bg:before").height($(document).height());
不起作用。
先谢了
3条答案
按热度按时间ih99xse11#
使用JavaScript,您可以通过这种方式修改
.bg:before
的规则。循环样式表中的规则,如果当前规则为
.bg:before
(r.selectorText == .bg:before
),则更改其height
(r.style.height = window.innerHeight + 'px'
)。webghufk2#
你不能用javascript,因为伪元素不是DOM的一部分。
q3qa4bjr3#
通过一个CSS变量从main元素传递一个值到pseudoelement。main元素可以通过javascript访问,然后计算并更新该值。您也可以设置一个备用值,直到该值更新为止,就像我在这里所做的那样(100%),或者在任何父元素的CSS中为CSS变量设置一个默认值。
所有这些都是代码:在伪类中使用
height: var(--bg-height, 100%);
,然后在JavaScript中使用element.style.setProperties('--bg-height',document.body.scrollHeight+'px');
。注意,如果你使用vanilla js(我在这里,现在是2022年),在计算文档高度的某些方法上会有一些箱模型的怪异之处。
完整的工作示例如下: