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

How do I apply these same CSS rules to JS?

本文关键字:CSS 规则 应用于 JS      更新时间:2023-09-26

我正在构建一个网站,我希望背景img拉伸到浏览器的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>

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

document.getElementById("background").style.width= "100%"
应用所有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>