gpt4 book ai didi

Javascript轮播,显示随机div并每3秒更改一次

转载 作者:行者123 更新时间:2023-11-30 14:24:23 26 4
gpt4 key购买 nike

我正在尝试创建一个显示随机 div 并每 3 秒更改一次的 Javascript 轮播。

我在加载时显示了随机 div,但不确定要添加什么才能使其更改为下一个。

  var elems = $("div");
if (elems.length) {
var keep = Math.floor(Math.random() * elems.length);
for (var i = 0; i < elems.length; ++i) {
if (i !== keep) {
$(elems[i]).hide();
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="content1">This is content 1</div>
<div id="content2">This is content 2</div>
<div id="content3">This is content 3</div>
<div id="content4">This is content 4</div>
<div id="content5">This is content 5</div>
<div id="content6">This is content 6</div>

最佳答案

将您的代码放在这样的间隔中:

setInterval(function(){
var elems = $("div");
if (elems.length) {
var keep = Math.floor(Math.random() * elems.length);
for (var i = 0; i < elems.length; ++i) {
if (i !== keep) {
$(elems[i]).hide();
}
else{
$(elems[i]).show();
}
}
}
},1000); // change every 1s ;

================================

更新

要在间隔开始之前隐藏所有 div,您有两种方法。

第一种方法是使用 css 。你可以添加一个 css 类到名为“hide-at-start”的 div 并像这样定义它:

.hide-at-start
{
display:none;
}

并将其添加到 div 中:

<div id="content1" class="hide-at-start">This is content 1</div>
<div id="content2" class="hide-at-start">This is content 2</div>
<div id="content3" class="hide-at-start">This is content 3</div>
<div id="content4" class="hide-at-start">This is content 4</div>
<div id="content5" class="hide-at-start">This is content 5</div>
<div id="content6" class="hide-at-start">This is content 6</div>

第二种方法是像这样通过 javascript 来完成:

 function showRandomDiv(){
var elems = $("div");
if (elems.length) {
var keep = Math.floor(Math.random() * elems.length);
for (var i = 0; i < elems.length; ++i) {
if (i !== keep) {
$(elems[i]).hide();
}
else{
$(elems[i]).show();
}
}
}
}

showRandomDiv(); // runs once

setInterval(showRandomDiv,1000); // change every 1s ;

不过我更喜欢第一种解决方案。

========================

更新

添加动画有很多种方法。例如,您可以像这样使用 css @keyframes :

@keyframes fade-in-from-left {
0% {left: 0px;opacity: 0;}
50% {left: 20px;opacity: 0.5;}
100%{left:0px;opacity: 1;}
}


.fade-in-from-left{
position: relative;
animation: fade-in-from-left 0.5s forwards;
}

然后将 fade-in-from-left 像这样添加到您的 div 中:

<div class="hide-at-start fade-in-from-left">This is content 1</div>
<div class="hide-at-start fade-in-from-left">This is content 2</div>
<div class="hide-at-start fade-in-from-left">This is content 3</div>
<div class="hide-at-start fade-in-from-left">This is content 4</div>
<div class="hide-at-start fade-in-from-left">This is content 5</div>
<div class="hide-at-start fade-in-from-left">This is content 6</div>

关于Javascript轮播,显示随机div并每3秒更改一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52179910/

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