gpt4 book ai didi

javascript - 从大数组中选择图片URL,插入页面随机DIV,循环

转载 作者:行者123 更新时间:2023-11-30 08:57:03 24 4
gpt4 key购买 nike

有点奇怪的请求。我有 ~300 个图像 URL 和 27 div秒。每个div有一个 id="img1" , 其中1是一个介于 1 和(你猜对了)27 之间的数字,和一个 class="imageblock" (用于一般样式)。

进入每一个div s,我想插入一个 <img src="http://foo.bar/img.jpg" width="640"> ,其中 URL 是从大约 300 个列表中随机选择的,并插入到 div 中的一个中。是随机的。每个 27 div s 应该从 300 个选项中选择自己的图像。

此外,这些图像应该循环。每 5 秒,我希望将页面上的一个随机图像 URL 替换为另一个随机图像 URL。

这是我试图在一点帮助下拼凑的(糟糕的)代码,但我对 javascript 毫无用处,无法完成这项工作:

<script type="text/javascript">     
$('document').ready(function() {
var divs = $('div');

$("div").each(function() {
$(this).html("<img src='http://foo.bar/img1.jpg'alt='"+$(this).attr("id")+"'/>");
});

var imageChanger = setInterval(function() {switchImage()}, 500);


function switchImage() {
var new_image_url = [ 'http://foo.bar/anotherimg.jpg', 'http://bar.foo/image.jpg', 'http://foo.bar/imgremote.jpg'];

var random_div = Math.floor(Math.random() * $('div').length);
var random_img = Math.floor(Math.random() * $(new_image_url.length);

$("div:nth-child("+random_div+")").html('<img src="('+random_img+')" width="640">)');

}
});
</script>

请注意,远程图像不遵循任何通用模式,因此呈现我的 random_img变量无效。

如有任何帮助,我们将不胜感激。

最佳答案

要从数组中选择一个随机元素,你可以使用这个:

var random_div = divs[Math.floor(Math.random() * divs.length)];
var random_img = new_image_url[Math.floor(Math.random() * new_image_url.length)];

这是您的代码的一个更高效的版本:

function random_int(max) {
return Math.floor(Math.random() * max);
}

$(document).ready(function() {
var images = ['http://foo.bar/anotherimg.jpg', 'http://bar.foo/image.jpg', 'http://foo.bar/imgremote.jpg'];
var $divs = $('div');

$divs.each(function() {
$('<img />', {
src: 'http://foo.bar/img1.jpg',
alt: this.id
}).appendTo(this);
});

function switchImage() {
var $div = $divs.eq(random_int($divs.length));
var image = images[random_int(images.length)];

$div.find('img').attr('src', image);
}

var imageChanger = setInterval(switchImage, 500);
});

关于javascript - 从大数组中选择图片URL,插入页面随机DIV,循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12649972/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com