我有一个带有背景图像的元素,是否可以将该背景图像更改为我拥有的随机图像URL?
因此,当用户加载页面时,会显示一个随机的背景图像。
更新
感谢回答我问题的每一个人,你们都很棒!
发布于 2012-05-19 11:00:22
是。下面是一个示例:
$(document).ready(function() {
$("body").css("background-image", "url("+your_random_image_url+")");
});
发布于 2012-05-19 11:02:15
将图像文件命名为"image1.jpg“"image2.jpg”,依此类推。生成随机数
Math.floor(Math.random()*range_of_your_image_nums+1);
然后使用这个数字加载随机图像,如下所示
$("#id_of_your_element").css("background","<url>");
发布于 2012-05-19 11:03:44
下面是执行此操作的示例脚本,下面是我执行此操作的方法。使用IE 6和Firefox (2和3)进行了测试。背景图像固定在正确的站点上,不会滚动。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Untitled</title>
<script type="text/javascript">
function changeImg(imgNumber) {
var myImages = ["images/image0.jpg", "images/image1.jpg", "images/image2.jpg", "images/image3.jpg"];
var imgShown = document.body.style.backgroundImage;
var newImgNumber =Math.floor(Math.random()*myImages.length);
document.body.style.backgroundImage = 'url('+myImages[newImgNumber]+')';
}
window.onload=changeImg;
</script>
<style type="text/css">
.bg {background-attachment:fixed; background-repeat: no-repeat; background-position:top right;}
</style>
</head>
<body class="bg">
<p>Some text</p>
<!-- put a lot text lines here to see that the background stays fixed. -->
<p>Some text</p>
</body>
</html>
https://stackoverflow.com/questions/10664575
复制