Javascript 随机身体背景图片
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8827691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Random body background-image
提问by asirgado
I've tried several tutorial on the web and none seems to work properly. What I'm trying to do is quite simple I think:
我在网上尝试了几个教程,但似乎没有一个可以正常工作。我想做的很简单,我认为:
I have 9 different .jpg images that I need to randomly show up on page load - to be background. This should be fairly simple right?
我有 9 个不同的 .jpg 图像,我需要在页面加载时随机显示它们 - 作为背景。这应该相当简单吧?
Thanks,
谢谢,
EDIT (Sorry, forgot to attach the code - found in the web):
编辑(对不起,忘了附上代码 - 在网上找到):
$(document).ready(function(){
bgImageTotal=9;
randomNumber = Math.round(Math.random()*(bgImageTotal-1))+1;
imgPath=('../img/bg/'+randomNumber+'.jpg');
$('body').css('background-image', ('url("'+imgPath+'")'));
});
回答by Jesse Pollak
Check out this tutorial: http://briancray.com/2009/12/28/simple-image-randomizer-jquery/
查看本教程:http: //briancray.com/2009/12/28/simple-image-randomizer-jquery/
First create an array of images:
首先创建一个图像数组:
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg', 'image5.jpg'];
Then, set a random image as the background image:
然后,设置一个随机图像作为背景图像:
$('body').css({'background-image': 'url(images/' + images[Math.floor(Math.random() * images.length)] + ')'});
That should work no problem.
那应该没问题。
回答by ChrisiPK
using jQuery: $("body").css("background-image", "url(" + Math.floor(Math.random()*9) + ".jpg)");
使用jQuery: $("body").css("background-image", "url(" + Math.floor(Math.random()*9) + ".jpg)");
This is assuming, that your images are named 0.jpg until 8.jpg and are in the same directory as your page.
这是假设您的图像命名为 0.jpg 到 8.jpg 并且与您的页面位于同一目录中。