[英]How to set height to an element with ::before selector with javascript?
有一個元素with.bg class。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());
不起作用。
提前致謝
使用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) } } }
.bg { width: 100%; } .bg::before { position: absolute; content: ''; background: rgba(0, 0, 0, 0.5); width: 100%; height: 100%; }
您根本無法使用javascript,因為偽元素不是DOM的一部分。
通過 CSS 變量將值從主元素傳遞到偽元素。 可以通過 javascript 訪問主要元素,並計算和更新該值。 您還可以設置一個回退值,直到該值被更新(您的 100%),或者通過在任何父元素的 CSS 中設置 CSS 變量的默認值。
所有這些都在代碼中:使用height: var(--bg-height, 100%);
在偽類中,然后使用element.style.setProperties('--bg-height',document.body.scrollHeight+'px');
在您的 javascript 中。
請注意,如果您使用 vanilla js(我在這里,它是 2022 年),則某些計算文檔高度的方法存在一些框模型怪異之處。
一個完整的工作示例如下:
let el = document.getElementById('example'); el.style.setProperty('--bg-height', document.body.scrollHeight+'px');
/************************************************* The CSS from the question. I lightened the grey (dropped the transparency from 0.5 to 0.25) and added a var for height. ***/.bg { width:100%; }.bg:before { position: absolute; content: ''; background: rgba(0,0,0,0.25); width: 100%; height: var(--bg-height, 100%); } /************************************************* Following is for this demo and can be removed. ***/:root { font: 16px Roboto, Helvetica, Barlow, sans-serif; } body { } a { color: #435; } section>p { max-width: 600px; margin: 1rem auto; }
<section class="bg" id="example"> <p>Here is a section that is the main element being focused on. It has a transparent (thus, white) background. There is a:before pseudoelement positioned absolutely over it with a highly transparent black (thus a light grey tint). Using javascript, this pseudoelement is set to a height equal to the document itself.</p> <p>Resizing and other things that would change the document height should be taken into account and observed.</p> <p>Answer to <a href="https://stackoverflow.com/questions/27358143/how-to-set-height-to-an-element-with-before-selector-with-javascript">How to set height to an element with::before selector with javascript?</a></p> </section>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.