我试图让计时器键入文本,删除它,并重复,通过标题标题数组循环。我可以写它一次,但我对定时器的有限理解阻碍了我。这是迄今为止我所拥有的。在将写入逻辑放入自己的方法之前,我可以从控制台手动调用writeText()插件,但现在只能使用一次。这里有一个link to a codepenJavascript setInterval /超时不工作
<!-- HTML -->
<div class="holder">
<h1><span>Lorem ipsum dolor sit amet, consectetur adipisicing </span><img id="cursor" src="https://copy.com/oBelwqiCr3Fa"></h1>
</div>
// Javascript
// counter and array of text to type in the header
var headerArray = [
"The Internet can't teach you about marketing",
"I wish I learned in art school",
"Every Successful Startup Eventually Does"
],
headerCounter = 0,
// headerContainer = $('.holder h1 span'),
headerContainer = document.querySelector('#cursor').previousElementSibling;
// function to type the text
function typeText(i) {
$('.holder h1 span').text('').writeText(headerArray[i]);
headerCounter++;
if (headerCounter >= headerArray.length) {
headerCounter = 0;
}
}
$(function() {
// fades cursor in and out
setInterval(function() {
$('#cursor').fadeToggle(400);
}, 400);
// calls function to type the text
setInterval(typeText(headerCounter), 5000);
});
// plugin that writes out the text like a typewriter
(function($) {
$.fn.writeText = function(content) {
var contentArray = content.split(""),
current = 0,
elem = this;
setInterval(function() {
if(current < contentArray.length) {
elem.text(elem.text() + contentArray[current++]);
}
}, 50);
};
})(jQuery);
// plugin that deletes text
(function($) {
$.fn.deleteText = function(content) {
var newContent = content.slice(0, content.length - 1),
current = 0,
elem = this;
setInterval(function() {
if (elem.text().length == 0) {
elem.text(newContent);
current--;
}
}, 50);
};
})(jQuery);
原因之一,这是不正确的:' setInterval(typeText(headerCounter),5000);'你需要传递一个函数给'setInterval'。相反,你正在调用它并传递'undefined'的返回值。 –
@se_puede_dev同意cookie_monster。检查http://codepen.io/anon/pen/DKuAE –