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

Modify CSS file using Math.Random();

本文关键字:修改 CSS 文件 Math Random 使用      更新时间:2023-09-26

我正在尝试使用

更改背景图像

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

在我的CSS文件中有一行在我的HTML文件中叫做:

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

设置背景图像

试试Jquery [fantastic]

现场演示 html:

<div class="slider"></div>
css:

.slider {
    width: 300px;
    height: 300px;
    -webkit-background-size:100% 100%;
    -moz-background-size:100% 100%;
    background-repeat:no-repeat;
    border: 2px black solid;
}

JavaScrip:

$(function () {
    var url = "http://maispc.com/samuel/content/images/",
        imgArray = [url+"avatar.png",
                   url+"provider/blogger.png",
                   url+"provider/LinkedIn-32x32.png",
                   url+"provider/myspace.png",
                   url+"provider/instagram.png",
                   url+"provider/Twitter-32x32.png",
                   url+"provider/stackoverflow.png",
                   url+"provider/Facebook-32x32.png"],
        randomNumber = Math.floor((Math.random() * imgArray.length)),
        baseUrl = "url('" + imgArray[randomNumber] + "')";
    $(".slider").css('background-image', baseUrl); })();

LIVE in fiddle

因为唯一改变的是背景图像,我只是使用javascript应用样式。就像

var randomNumber = Math.floor((Math.random()*4)+1),
    sliders = document.getElementsByClassName('slider');
Array.prototype.forEach.call(sliders, function (elm) {
  elm.style.background = 'url(images/slide-img' + randomNumber + '.png)';
});
  • 未测试