我不是javascripter。我知道足够复制,粘贴和修补。但是我无法充分理解这个脚本添加一个setTimeout,从W3示例开始。
这是我用于文本类型动画的脚本。我想把功能延迟几毫秒。我怎么能这样做?
<script type="text/javascript">
var TxtType = function(el, toRotate, period) {
this.toRotate = toRotate;
this.el = el;
this.loopNum = 0;
this.period = parseInt(period, 8) || 200;
this.txt = '';
this.tick();
this.isDeleting = false;
};
TxtType.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 - 2.5);
} else {
this.txt = fullTxt.substring(0, this.txt.length + 1);
}
this.el.innerHTML = '<span class="wrap">'+this.txt+'</span>';
var that = this;
var delta = 122 - Math.random() * 110;
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 = 900;
}
setTimeout(function() {
that.tick();
}, delta);
};
window.onload = function() {
var elements = document.getElementsByClassName('typewrite');
for (var i=0; i<elements.length; i++) {
var toRotate = elements[i].getAttribute('data-type');
var period = elements[i].getAttribute('data-period');
if (toRotate) {
new TxtType(elements[i], JSON.parse(toRotate), period);
}
}
// INJECT CSS
var css = document.createElement("style");
css.type = "text/css";
css.innerHTML = ".typewrite > .wrap { border-right: 0.08em solid #fff}";
document.body.appendChild(css);
};
答案 0 :(得分:1)
要使用setTimeout
延迟功能,您需要执行以下操作:
var myFunction = function() {
// awesome stuff
};
setTimeout(myFunction, 1000);
这将在经过1000毫秒后运行myFunction
。
您还可以将要匿名延迟的函数定义为setTimeout
的第一个参数,如下所示:
setTimeout(function() {
// awesome stuff
}, 1000);
使用setTimeout
的这两个版本是identicle。