javascript - 使用 Math.Random() 修改 CSS 文件;

标签 javascript html css

我正在尝试使用

更改背景图片

Math.floor((Math.random());

在我的 HTML 文件中调用的 CSS 文件中的一行是:

.slider { width: 990px;  height: 378px; position: relative;  background: url(images/slide-img.png) no-repeat 0 0;}

我想要做的是使用以下语句获取从 1 到 4 的随机数,并根据随机检索到的数字显示不同的背景图像。所以我决定从 CSS 文件中删除上面的行,并在我的 HTML 文件中添加以下代码:

var randomNumber = Math.floor((Math.random()*4)+1); // random number (no more than 4 or the array will be out of bounds)
if (randomNumber == 1) {
    document.write ('<style>.slider { width: 990px;  height: 378px; position: relative;  background: url(images/slide-img.png) no-repeat 0 0;}</style>');
}
if (randomNumber == 2) {
    document.write ('<style>.slider { width: 990px;  height: 378px; position: relative;  background: url(images/slide-img2.png) no-repeat 0 0;}</style>');
}
if (randomNumber == 3) {
    document.write ('<style>.slider { width: 990px;  height: 378px; position: relative;  background: url(images/slide-img3.png) no-repeat 0 0;}</style>');
}
if (randomNumber == 4) {
    document.write ('<style>.slider { width: 990px;  height: 378px; position: relative;  background: url(images/slide-img4.png) no-repeat 0 0;}</style>');
}

这产生了一个空白的 HTML 页面。我试图在不使用上述方法创建四个单独的 CSS 文件的情况下执行此操作。

最佳答案

document.write 将替换当前内容。页面的大小。

使用:document.getElementsByClassName('slider') 遍历元素并使用 element.style.backgroundImage=... 设置背景图像

关于javascript - 使用 Math.Random() 修改 CSS 文件;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16972517/

相关文章:

javascript - 如何让脚本在网页上最后加载?

html - 从 HTML 转换为 RTF 时如何强制 Word 嵌入图像?

jquery - CSS 菜单半左半右浮动

html - 使背景图像响应移动布局,但将其保持在固定位置

javascript - 以两种不同形式替换文本,如何通过其 div 访问嵌套标签中的文本

javascript - Owl Carousel/flex 轮播

JavaScript 返回时间不正确

javascript - 如何在 Three.js 中设置可见性动画?

html - 在带有 NodeJS 电子邮件模板的邮件中使用 Google 字体

javascript - 悬停时图像更改/放大而不影响页面间距