2014-10-10 50 views
-2

我正在建設一個網站,我想要背景img伸展到100%高度x寬度的瀏覽器,並且在刷新時交替隨機圖像;我目前瞭解如何使用div來製作一張img圖片,並且只使用CSS,我也知道如何使用JS來替換不同的圖片(我對JS一無所知,我使用了這個)。問題是,我不知道如何將CSS規則應用於JS,我只知道如何將它們應用於HTML。有人可以告訴我如何將這些相同的CSS規則應用於JS?我將在下面發佈CSS,DIV(包含一個背景圖像)和JS(帶有交替圖像,但沒有CSS規則)以供澄清。我真的很看重你們的投入!謝謝!如何將這些相同的CSS規則應用於JS?

<div id="background"> 
<img src="images/2.jpg" class="stretch" alt="#" /></div> 

#background{ 
width: 100%; 
height: 100%; 
position: fixed; 
left: 0px; 
top: 0px; 
z-index: -1; 
} 

.stretch { 
width:100%; 
height:100%; 
} 

<script type = "text/javascript"> 
    <!-- 
    document.write("<img src= \""+Math.floor(1+Math.random()*5)+".jpg\"/>"); 
    //--> 
</script> 

回答

0

您可以使用下面的JavaScript。(你需要寫一行每個PROPERT)

document.getElementById("background").style.width= "100%" 
+0

我在哪裏將它包含到腳本中?有沒有特定的地方? – Jake 2014-10-10 05:25:35

+0

只需將其添加到'

0

更好的方式來應用所有的CSS規則是包含在類中的所有規則然後使用Js將該類添加到該元素。

<div id="background"> 
<img src="images/2.jpg" alt="#" id="stretch" /></div> 

.background{ 
width: 100%; 
height: 100%; 
position: fixed; 
left: 0px; 
top: 0px; 
z-index: -1; 
} 

.stretch { 
width:100%; 
height:100%; 
} 

<script type = "text/javascript"> 

    document.write("<img src= \""+Math.floor(1+Math.random()*5)+".jpg\"/>"); 
    document.getElementById("background").setAttribute("class", "background"); 
    document.getElementById("stretch").setAttribute("class", "stretch"); 

</script> 
相關問題