2017-06-03 136 views
0

嗨我試圖根據屏幕大小更改僞元素的樣式,但我相信我的語法在某處出錯。我谷歌的問題,但無法找到確切的解決方案。以下是我的CSS-使用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! 
+0

[通過JavaScript更改CSS僞元素款式]的可能的複製(https://stackoverflow.com/questions/4481485/changing-css-pseudo-element- styles-via-javascript) –

回答

0

使用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須藤元素的樣式是不可能的。您可以添加樣式標籤的頭部,但:

<script> 
if (calculatedWidth > 900) { 
    document.styleSheets[0].addRule('.cBox:before', 'border-left: 0 solid transparent'); 
} 
</script> 
+0

嗨感謝您的回放!其實我想設置左邊等於屏幕大小的一半,這就是爲什麼我想用js。我再次更新了這個問題。請看一看。 –

+0

請檢查編輯答案 –