简体   繁体   English

Javascript随机背景图片

[英]Javascript Random background Image

I have written this with the intention of randomising a background image each time a user visits a site. 我写这篇文章的目的是在用户每次访问站点时随机化背景图像。 I had to use Ajax as the image is being used as a background image in css with some animations. 我必须使用Ajax,因为该图像在CSS中被用作带有某些动画的背景图像。

var images = [
  '1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg'];

var randomNumber = Math.floor(Math.random() * images.length);
var randomImage = "img/backgrounds/" + randomNumber + ".jpg";
jQuery.ajax(randomImage);

$(document).ajaxComplete(function() {
    $('.cover').css({ 'background-image': 'url(' + randomImage + ')' }).addClass('loaded');
});

My problem is that some images seem to be used a lot more often that others and image number 6 never shows? 我的问题是,某些图像似乎比其他图像更经常使用,而图像编号6从未显示?

I was hoping someone who is more comfortable in Javascript might be able to shed some light on this for me. 我希望有人对Java更加熟悉,也许可以为我提供一些启示。

Thanks in advance, Sam 预先感谢,山姆

The range of variable randomNumber is 0 to 5 (inclusive). 变量randomNumber的范围是05 (含)。 They are the indexes where you want to fetch the value from the array images : 它们是您要从数组images获取值的索引:

var randomImage = "img/backgrounds/" + images[randomNumber];

将您的随机数更改为var randomNumber = Math.floor((Math.random()* images.length)+1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM