Npcink Blog
切换菜单

JS 实现动态打字效果 - js 笔记

本页目录3 节

打字特效算是一种比较常用的 JS 特效了,一起来看看他们是怎么实现的吧。

只打印单纯的文字(1)

原网页中的可执行演示已停用,以下完整保留为静态 HTML 代码。

<div id="text">
</div>
<script>
let divTyping = document.getElementById('text')
let i = 0,
timer = 0,
str = '用JS实现动态打字效果,刷新本页面重复'
function typing () {
if (i <= str.length) {
divTyping.innerHTML = str.slice(0, i++) + '_'
timer = setTimeout(typing, 200)
}
else {
divTyping.innerHTML = str//结束打字,移除 _ 光标
clearTimeout(timer)
}
}
typing()
</script>

打印带标签的段落(2)

无

纯 JS 自动打字特效(3)

原网页中的可执行演示已停用,以下完整保留为静态 HTML 代码。

<!--复制开始-->
<!--
版本:1.0
整理:Muze
帮助:https://www.npc.ink/15555.html
-->
<h1>Npcink
<span class="txt-rotate" data-period="2000" data-rotate="[ &quot;提供优秀的wordpress主题、插件&quot;, &quot;提供优秀的Typecho主题、插件&quot;, &quot;促进国内wordpress发展&quot;, &quot;促进小白站长快速成长&quot;, &quot;助力国内互联网进步&quot; ]"></span>
</h1>
<script type="text/javascript">
var TxtRotate = function(el, toRotate, period) {
this.toRotate = toRotate;
this.el = el;
this.loopNum = 0;
this.period = parseInt(period, 10) || 2000;
this.txt = '';
this.tick();
this.isDeleting = false;
};
TxtRotate.prototype.tick = function() {
var i = this.loopNum % this.toRotate.length;
var fullTxt = this.toRotate[i];
if (this.isDeleting) {
this.txt = fullTxt.substring(0, this.txt.length - 1);
} else {
this.txt = fullTxt.substring(0, this.txt.length + 1);
}
this.el.innerHTML = '<span class="wrap">'+this.txt+'</span>';
var that = this;
var delta = 300 - Math.random() * 100;
if (this.isDeleting) { delta /= 2; }
if (!this.isDeleting && this.txt === fullTxt) {
delta = this.period;
this.isDeleting = true;
} else if (this.isDeleting && this.txt === '') {
this.isDeleting = false;
this.loopNum++;
delta = 500;
}
setTimeout(function() {
that.tick();
}, delta);
};
window.onload = function() {
var elements = document.getElementsByClassName('txt-rotate');
for (var i=0; i<elements.length; i++) {
var toRotate = elements[i].getAttribute('data-rotate');
var period = elements[i].getAttribute('data-period');
if (toRotate) {
new TxtRotate(elements[i], JSON.parse(toRotate), period);
}
}
// INJECT CSS
var css = document.createElement("style");
css.type = "text/css";
css.innerHTML = ".txt-rotate > .wrap { border-right: 0.08em solid #666 }"; //光标样式
document.body.appendChild(css);
};
</script>
<!--复制到此为止-->

想看源代码的自行 F12