Javascript 如何将这些相同的CSS规则应用于JS?

Javascript 如何将这些相同的CSS规则应用于JS?,javascript,html,css,rotation,Javascript,Html,Css,Rotation,我正在建设一个网站,我希望背景图像延伸到100%的高度x浏览器的宽度,并在刷新时交替随机图像;我现在知道如何使用div和CSS来拉伸img,我也知道如何使用JS来替换不同的图像(我对JS一无所知,我在谷歌上搜索过这个)。问题是,我不知道如何将CSS规则应用于JS,我只知道如何将它们应用于HTML。有人能告诉我如何将同样的CSS规则应用于JS吗?我将在下面发布CSS、DIV(包含一个背景img)和JS(带有交替图像,但没有CSS规则)以供澄清。我真的很重视你们的意见!谢谢 <div id="

我正在建设一个网站,我希望背景图像延伸到100%的高度x浏览器的宽度,并在刷新时交替随机图像;我现在知道如何使用div和CSS来拉伸img,我也知道如何使用JS来替换不同的图像(我对JS一无所知,我在谷歌上搜索过这个)。问题是,我不知道如何将CSS规则应用于JS,我只知道如何将它们应用于HTML。有人能告诉我如何将同样的CSS规则应用于JS吗?我将在下面发布CSS、DIV(包含一个背景img)和JS(带有交替图像,但没有CSS规则)以供澄清。我真的很重视你们的意见!谢谢

<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>

#背景{
宽度:100%;
身高:100%;
位置:固定;
左:0px;
顶部:0px;
z指数:-1;
}
.伸展{
宽度:100%;
身高:100%;
}

您可以使用以下javascript。(您需要为每个属性写一行)


应用所有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>

.背景{
宽度:100%;
身高:100%;
位置:固定;
左:0px;
顶部:0px;
z指数:-1;
}
.伸展{
宽度:100%;
身高:100%;
}
文件。填写(“”);
document.getElementById(“背景”).setAttribute(“类”、“背景”);
document.getElementById(“拉伸”).setAttribute(“类”、“拉伸”);

我应该在脚本中的什么位置包含这些内容?是否有特定的位置?只需将其添加到“”标记中即可。如果答案对你有帮助,也请把它标记为答案。
<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>