启动此功能时遇到一些问题我做错了什么?
我想在菜单到达“topb”部分时开始写作。
这是我的尝试:
var $el = $('.writer'),
txt = $el.text(),
txtLen = txt.length,
timeOut,
$topb = $('#topb'),
char = 0;
$el.text('|');
if (topb.hasClass('active')) {
(function typeIt() {
var humanize = Math.round(Math.random() * (200 - 30)) + 30;
timeOut = setTimeout(function () {
char++;
var type = txt.substring(0, char);
$el.text(type + '|');
typeIt();
if (char == txtLen) {
$el.text($el.text().slice(0, -1)); // remove the '|'
clearTimeout(timeOut);
}
}, humanize);
}())
};
这是原始功能
var $el = $('.writer'),
txt = $el.text(),
txtLen = txt.length,
timeOut,
char = 0;
$el.text('|');
(function typeIt() {
var humanize = Math.round(Math.random() * (200 - 30)) + 30;
timeOut = setTimeout(function () {
char++;
var type = txt.substring(0, char);
$el.text(type + '|');
typeIt();
if (char == txtLen) {
$el.text($el.text().slice(0, -1)); // remove the '|'
clearTimeout(timeOut);
}
}, humanize);
}())
};
答案 0 :(得分:1)
原始代码使用计时器重复操作,直到满足某个条件(递归调用自身)。您已将if
支票放在该支票之外,因此它永远不会运行。
在计时器内进行检查,以便反复检查。像这样:
var $el = $('.writer'),
txt = $el.text(),
txtLen = txt.length,
timeOut,
$topb = $('#topb'),
char = 0;
$el.text('|');
(function typeIt() {
if ($topb.hasClass('active')) {
var humanize = Math.round(Math.random() * (200 - 30)) + 30;
timeOut = setTimeout(function () {
char++;
var type = txt.substring(0, char);
$el.text(type + '|');
typeIt();
if (char == txtLen) {
$el.text($el.text().slice(0, -1)); // remove the '|'
clearTimeout(timeOut);
}
}, humanize);
}
else{
// do nothing but repeat the timer (e.g. after 2 seconds)
timeOut = setTimeout(typeIt, 2000);
}
}());