随机div内容+背景

时间:2017-10-07 03:44:39

标签: jquery html css

这是我的随机div background-image的代码。我只是想知道如何为每个div添加某些说明background

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


$(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", ".tab").css('background-image', baseUrl);
})();

就像这样

{ $(function () {
var url = "http://maispc.com/samuel/content/images/",
    imgArray = [url+"avatar.png",
               url+"provider/blogger.png", description div 1
               url+"provider/LinkedIn-32x32.png",description div 2
               url+"provider/myspace.png", and so ....
               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);
})();

} 

1 个答案:

答案 0 :(得分:0)

制作一个包含所有描述的数组。

HTML:

<div class="slider">
    <div class="description"></div>
</div> 

JS:

$(function () {
    var url = "http://maispc.com/samuel/content/images/";
    var 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"];
    var descriptionArray = ["Description 1",
               "Description 2",
               "Description 3",
               "Description 4",
               "Description 5",
               "Description 6",
               "Description 7",
               "Description 8"];
    var randomNumber = Math.floor((Math.random() * imgArray.length));
    var baseUrl = "url('" + imgArray[randomNumber] + "')";
    var description = descriptionArray[randomNumber];
    $(".slider").css('background-image', baseUrl);
    $(".description").text(description);
})();