下面是另一个用户在此处编写的代码,用于显示/隐藏具有 4-8 秒之间随机延迟的 div
<script>
function showCity() {
$('#city-middle').show();
window.setTimeout( hideCity, 10 );
}
function hideCity() {
$('#city-middle').fadeOut(200);
window.setTimeout( showCity, 3000 + (Math.random() * 5000) );
}
hideCity();
</script>
所以 DIV #city-middle(出现并淡出)有一个名为 #bolt-container 的子 div,它显然随该 div 一起出现和淡出。在这个 bolt 容器中有 4 个名为 bolt-1 到 bolt-4 的子 div。这些 div 中的每一个都位于不同的位置。
<div id="city-middle">
<div id="bolt-container">
<div class="bolt-1">
</div>
<div class="bolt-2">
</div>
<div class="bolt-3">
</div>
<div class="bolt-4">
</div>
</div>
</div>
我需要的是让#bolt-1 - #bolt-4 div 一次随机出现一个,没有动画。
到目前为止,我用谷歌搜索了这个,只发现了一个可能有帮助的 jsfiddle - http://jsfiddle.net/tricinel/FgXDC/
我试过如下实现但没有成功。
function showCity() {
$('#city-middle').show();
window.setTimeout( hideCity, 10 );
}
function hideCity() {
$('#city-middle').fadeOut(200);
window.setTimeout( showCity, 3000 + (Math.random() * 5000) );
}
hideCity();
var divs = $('#bolt-container').find('.div'),
len = divs.length,
randomDiv,
speed = 1000;
var interval = setInterval(
function() {
randomDiv = Math.floor(Math.random()*len);
divs.removeClass('show');
divs.eq(randomDiv).addClass('show');
} , speed);
我知道我的布局方式有问题,但作为初学者,我什至不知道去哪里看!可能是我没有正确关闭第一个 jQuery 东西吗?或者不为第二个设置某种形式的功能?
最佳答案
要调整您发布的 fiddle ,您只需使用:
var divs = $('#bolt-container').find('div'), //fetch all the divs
注意 var divs = $('#bolt-container').find('.div')
使用 div
获取所有元素class(!) 是 ID 为 #bolt-container
的元素的后代.在你的例子中,你不想要那个,你想要获取所有 <div>
在这样的元素之下。这就是上面改编的代码所做的。
不要忘记 CSS(也将应用于 <div>
下面的所有 #bolt-container
):
#bolt-container div {
display:none;
}
关于jquery - 如何随机显示一个div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17756816/