1. 程式人生 > 實用技巧 >基於jQuery的打字機函式

基於jQuery的打字機函式

<!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head> <body>
<div id="pic" style="display: none;">
這是一段打字機效果的文字
</div> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
(function ($) {
$.fn.typewriter = function () {
this.each(function () {
var $ele = $(this),
str = $ele.html(),
progress = 0;
$ele.html('');
var timer = setInterval(function () {
var current = str.substr(progress, 1);
if (current == '<') {
progress = str.indexOf('>', progress) + 1;
} else {
progress++;
}
$ele.html(str.substring(0, progress) + (progress & 1 ? '_' : ''));
if (progress >= str.length) {
clearInterval(timer);
}
}, 150);
});
return this;
};
})(jQuery); $("#pic").show().typewriter(50);
</script>
</body> </html>