一款支持多文本段落的jQuery打字效果,可以自由添加多个段落、设置打字的速度,自动计算每个段落的打字耗时,配上语音效果,就变成了“为你读书”的功能了,喜欢的童鞋请收下吧。
页面的head部分,需要先引入jQuery库,代码如下:
<script type="text/javascript" src="js/jquery.min.js"></script>
接着设置好页面元素的样式,标题、段落等,代码如下:
body, html {
margin: 0;
height: 100%;
text-align: center;
font-family: 'Microsoft YaHei','Lantinghei SC','Open Sans',Arial,'Hiragino Sans GB','STHeiti','WenQuanYi Micro Hei','SimSun',sans-serif;
color: #999;
}
h1 {
text-align: center;
letter-spacing: 1pt;
font-size: 30px;
font-weight: 500;
margin-top: 10%;
margin-bottom: 15px;
}
p {
text-align: justify;
text-indent: 2em;
margin: 0;
font-size: 16px;
font-weight: 500;
width: 60%;
display: none;
line-height: 28px;
}
页面的底部,这里提供了两种方法解决setTimeout的执行顺序,一种是ES6的let块作用域,另一种是自执行函数提供闭包条件,这样就能避免同时执行多个段落的setTimeout的问题了,值得借鉴学习一下,代码如下:
function typeEffect(element, speed) {
var text = $(element).text();
$(element).html('');
let i = 0;
var timer = setInterval(function() {
if (i < text.length) {
$(element).append(text.charAt(i));
++i;
} else {
clearInterval();
}
}, speed);
}
$( document ).ready(function() {
var speed = 72;
var sum = 0;
var delay = new Array();
$('#typeist').children().each(function(){
sum += ($(this).text().length-1) * speed + speed;
delay.push(sum);
});
var plen = delay.length;
typeEffect($('h1'), speed);
/* 方法一:使用let块作用域 */
for (let i = 2; i <= plen; ++i){
setTimeout(function(){
$('p:nth-child('+i+')').css('display', 'inline-block');
typeEffect($('p:nth-child('+i+')'), speed);
}, delay[i-2]);
}
/* 方法二:使用自执行函数提供闭包条件
for (var i = 2; i <= plen; ++i){
(function(i){
setTimeout(function(){
$('p:nth-child('+i+')').css('display', 'inline-block');
typeEffect($('p:nth-child('+i+')'), speed);
}, delay[i-2]);
})(i);
}*/
});
系统已开启自动识别垃圾评论机制,识别到的自动封号,下载出错或者资源有问题请联系全栈客服QQ 1915635791