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

时间:2018-09-05 07:52:33

标签: javascript html carousel

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

我在加载时显示了随机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>

1 个答案:

答案 0 :(得分:2)

以这样的间隔放置代码:

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 ;

但是我更喜欢第一种解决方案。

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

UPDATE

添加动画有很多方法。例如,您可以像这样使用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;
}

然后像这样将从左渐入添加到您的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>