本文介绍了如何在网页中实现字符逐个显示的打字机动画效果。首先解析了基于定时器逐字添加字符的原生实现思路,并提供了简单的jQuery封装示例。随后推荐了功能更完善的jQuery插件Typed.js,详细列出了其核心配置参数如typeSpeed、startDelay等,帮助开发者快速集成该特效。
原生JavaScript实现打字机效果
近期网络上流行一种字符逐字显现的打字机动画特效,这种视觉效果颇具趣味性。其核心实现逻辑相对直观:通过设定一个定时器,按指定频率依次向目标容器内追加字符。基于这一思路,可以使用jQuery编写一个基础版本的实现方案。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>AutoType</title>
</head>
<body>
<div id="autotype"></div>
<script src="https://cdn.bootcss.com/jquery/1.9.1/jquery.min.js"></script>
<script>
$.fn.autotype = function (str, speed) {
var self = this,
defaultStr = '<p>我希望有个如你一般的人.</p><br>'
+'<p>如山间清爽的风.</p><br>'
+'<p>如古城温暖的光.</p><br>'
+'<p>从清晨到夜晚.</p><br>'
+'<p>由山野到书房.</p><br>'
+'<p>只要最后是你,就好.</p><br>',//将要添加的元素的默认内容
defaultSpeed = 100,
str = str || defaultStr,
speed = speed || defaultSpeed,
index = 0,
timer = setInterval(function () {
var current = str.substr(index, 1);
if (current == '<') {
index = str.indexOf('>', index) + 1;
} else {
index++;
}
self.html(str.substring(0, index) + ( (index & 1) && (index != str.length) ? '_' : ''));
if (index >= str.length) {
clearInterval(timer);
}
}, speed);
};
$("#autotype").autotype();
</script>
</body>
</html>
考虑到自行编写的代码可能较为简陋,经过资料检索发现,存在一款名为Typed.js的jQuery插件,其功能更为完善。
使用Typed.js插件简化开发
接下来介绍Type.js插件的基础使用方法。
<script src="jquery.js"></script>
<script src="typed.js"></script>
<script>
$(function(){
$(".element").typed({
strings: ["First sentence.", "Second sentence."],
typeSpeed: 0
});
});
</script>
...
<span class="element"></span>
该插件提供了丰富的默认配置选项与多种预设效果,用户可根据需求进行定制。
<script>
$(function(){
$(".element").typed({
strings: ["First sentence.", "Second sentence."],
// Optionally use an HTML element to grab strings from (must wrap each string in a <p>)
stringsElement: null,
// typing speed
typeSpeed: 0,
// time before typing starts
startDelay: 0,
// backspacing speed
backSpeed: 0,
// shuffle the strings
shuffle: false,
// time before backspacing
backDelay: 500,
// loop
loop: false,
// false = infinite
loopCount: false,
// show cursor
showCursor: true,
// character for cursor
cursorChar: "|",
// attribute to type (null == text)
attr: null,
// either html or text
contentType: 'html',
// call when done callback function
callback: function() {},
// starting callback function before each string
preStringTyped: function() {},
//callback for every typed string
onStringTyped: function() {},
// callback for reset
resetCallback: function() {}
});
});
</script>
具体用法可以看看GitHub地址,带注释的源码400多行,不算复杂。
以上即为本文的全部内容,期望这些内容能对各位的学习或工作有所助益,同时也欢迎大家继续支持本站。