我正在尝试使用
更改背景图片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/