2014-10-10 39 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> 
相关问题