首页 > 解决方案 > Html:从数组中选择随机字符串并延迟一一显示

问题描述

我有返回字符串的代码,但我想随机显示字符串。如果你有更好的代码,干杯。主要任务是有一个单词列表,以及一个以随机顺序显示这些单词的脚本,但不会用另一个单词替换一个单词,即一个接一个。延迟应该是可配置的。

$("#slideShow .fadeInAmate").each(function(i) {
  $(this).delay(200 * i).fadeIn(2000, function() {
    $(this).prev().addClass('foo');
  });
});
#slideShow p {
  display: none;
}

.foo {
  color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://jforaker.github.io/jQuery-FadeInAmate/src/jquery.fadeInAmate.js"></script>

<div id="slideShow">
  <p class="fadeInAmate">This is my first line</p>
  <p class="fadeInAmate">Here goes my second line</p>
  <p class="fadeInAmate">Then comes third line</p>
  <p class="fadeInAmate">Following to that fourth line</p>
  <p class="fadeInAmate">And finally here goes my fifth line</p>
</div>

标签: javascripthtmljquery

解决方案


先简单地打乱 HTML 元素Math.random(),然后再使用您的代码。

function shuffle(){
  var slideShow = $(".fadeInAmate");
  for(var i = 0; i < slideShow.length; i++){
    var target = Math.floor(Math.random() * slideShow.length -1) + 1;
    var target2 = Math.floor(Math.random() * slideShow.length -1) +1;
    slideShow.eq(target).before(slideShow.eq(target2));
  }
}

function animate(){
  $("#slideShow .fadeInAmate").each(function(i) {
    $(this).delay(200 * i).fadeIn(2000, function() {
      $(this).prev().addClass('foo');
    });

  });
}

shuffle();
animate();
<!DOCTYPE html>
<html>
<head>
<style>
    #slideShow p {
display: none;
}

.foo {
color: #000;
}
</style>
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://jforaker.github.io/jQuery-FadeInAmate/src/jquery.fadeInAmate.js"></script>
<div id="slideShow">
<p class="fadeInAmate">This is my first line</p>
<p class="fadeInAmate">Here goes my second line</p>
<p class="fadeInAmate">Then comes third line</p>
<p class="fadeInAmate">Following to that fourth line</p>
<p class="fadeInAmate">And finally here goes my fifth line</p>
</div>

</body>
</html>    


推荐阅读