[英]Apply style to css pseudo element using javascript
嗨,我試圖根據屏幕大小更改偽元素的樣式,但我認為我的語法在某處是錯誤的。 我用谷歌搜索問題,但找不到確切的解決方案。 以下是我的CSS-
.cBox{background-color: #efeff0; margin: 15px 0px -80px 0px;
display: inline-block;
margin-left: -8px;
margin-top: 55px;
position: relative;
width: 101%;}
.cBox:before{
border-bottom: 45px solid #efeff0;
border-left: 650px solid transparent;
border-right: 650px solid transparent;
content: "";
height: 0px;
left: 0;
position: absolute;
top: -45px;
width: 0px;}
Now the border left property of cBox:before should have half value of the screen size i.e. if screen size is 1300px, then border left should have a value of 650px(border-left:650px). below is my HTML-
<body onload="myFunction()">
<div class="cBox">
<div style="text-align:center;">Some text here</div>
</div>
<script>
function myFunction(){
var x = window.getComputedStyle(document.querySelector('.cBox')
,':before').getPropertyValue('border-left');
if(window.outerWidth >=900) x[0].style.borderLeft = "screen.availWidth/2px solid transparent";
else {x[0].style.borderLeft = "screen.availWidth/2px solid transparent"; }
}
</script>
</body>
I know x[0].style.borderLeft syntax is not correct please suggest!
使用CSS媒體查詢來設置不同屏幕尺寸(而不是JS)的樣式。
<style>
.cBox:before { border-left: 250px solid transparent; }
@media(min-width: 900px) {
.cBox:before { border-left: 0 solid transparent; }
}
</style>
參考: https : //developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries
無法使用JS修改sudo元素的樣式。 您可以將樣式標簽添加到頭部:
<script>
if (calculatedWidth > 900) {
document.styleSheets[0].addRule('.cBox:before', 'border-left: 0 solid transparent');
}
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.