<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>substring练习</title>
<style type="text/css">
.p-text p {
display: none;
}
</style>
</head>
<body>
<div class="p-text">
<p>打团可以输</p>
<p>鲁班必须死</p>
</div>
<p class="showText">
</p>
<script type="text/javascript">
var text1 = document.querySelector('.p-text p:first-child');
var text2 = document.querySelector('.p-text p:last-child');
console.log(text1, text2);
var showText = document.querySelector('.showText');
var i = 0;
var timer1 = setInterval(sub, 500);
function sub() {
showText.innerText = text1.innerText.substring(0, i);
i++;
console.log(i);
if(showText.innerText === text1.innerText) {
clearInterval(timer1);
var j = 0;
timer2 = setInterval(function() {
showText.innerText = text2.innerText.substring(0, j);
j++;
if(showText.innerText === text2.innerText) {
i = 0;
clearInterval(timer2);
timer1 = setInterval(sub, 500);
}
}, 500)
}
}
</script>
</body>
</html>
上述运行结果: