我正在尝试使用更改背景图像
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文件。
最佳答案
试试Jquery [很棒]
在中进行现场演示
的HTML:
CSS:
JavaScript:
在fiddle中进行现场演示