javascript - 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>
解决方案
先简单地打乱 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>
推荐阅读
- c++ - 将继承的结构传递给 poll()
- azure-active-directory - 我是否应该明确不使用标准 URL 和 MSAL 身份验证?
- zend-framework - 带有 ZF3 错误值的 ReCaptcha
- javascript - 无法使用 this.setState() 中的扩展运算符更新 json 属性 - React.js
- android-studio - 我可以在 2GB RAM 上正确运行 Android Studio 3.2(最新版本)吗?
- javascript - 截断 div 内的多个段落但保留 html 格式
- r - 如何在 R 中导入杂乱的数据?
- bash - 在评估文件以设置单个命令的环境变量时,如何支持注释?
- javascript - 即时创建 DIV 后超链接不起作用
- php - 获取pdf的页面宽度和高度