javascript - Make 'cursor' blink and fadeOut using jquery for typewriter effect
问题描述
I am using jquery to set up a typewriter effect on a div. I am not using css to do this because the sentence will be cover more than 1 line. The problem I am facing is getting the cursor to blink, then fade away when line is typed.
Html:
<div class="typewriter">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>
JS
/*****Start Typewriter effect*****/
$('.typewriter').css('display', 'none');
setTimeout(function(){
$('.typewriter').css('display', 'flex');
var str = $('.typewriter').html() + 1,
i = 0,
isTag,
text,
cursor = "|",
timer;
(function type() {
text = str.slice(0, ++i);
if (text === str){
return;
}
$('.typewriter').html(text + " " + cursor);
timer = setTimeout(type, 40);
}());
}, 300);
/*****End Typewriter effect*****/
Here is a jsfiddle https://jsfiddle.net/ht4569wv/
解决方案
Just validate when the effect you already made is done and set up another timer to blink the cursor:
/*****Start Typewriter effect*****/
$('.typewriter').css('display', 'none');
setTimeout(function(){
$('.typewriter').css('display', 'flex');
var str = $('.typewriter').html(),
i = 0,
isTag,
text,
cursor = "|",
timer;
(function type() {
text = str.slice(0, ++i);
if (text === str){
i = 0;
blink();
return;
}
$('.typewriter').html(text + " " + cursor);
timer = setTimeout(type, 40);
}());
function blink() {
i++;
const foo = str + " " + (i%2 ? cursor : '');
$('.typewriter').html(foo);
if (i < 10) timer = setTimeout(blink, 600);
else fade();
}
function fade() {
$('.typewriter').html(str);
}
}, 300);
/*****End Typewriter effect*****/
推荐阅读
- angular - 如何在Angular中实时异步地从REST API获取数据
- reactjs - 当 redux 同级状态发生变化时防止组件重新渲染
- ms-access - 查询是只读的,可能是由于聚合值
- google-cloud-platform - GCP 中目标池的用途
- variables - 通过 CMD 为整个子网远程启用和启动服务
- ruby-on-rails - 如何消除erb中的换行符
- python-3.x - 努力让 selenium 等到链接可点击 - 得到“在(x,y)处不可点击”错误
- delphi - TMemo:查找并复制两个单词之间的单词
- swift - SwiftUI:在 macOS NavigationView 中关闭视图
- pandas - 如何使用 auto_arima 跳过特定日期