所以我自己的解决方案是。但是,如果文本太长,这将变得乏味。
var typeThis = "blablablablabla:";
var displayText = "";
function type(fullString, typedSoFar) {
if (fullString.length != typedSoFar.length) {
typedSoFar = fullString.substring(0, typedSoFar.length + 1);
document.getElementById(".animatedTyping").innerText = typedSoFar;
setTimeout(function() {
type(fullString, typedSoFar)
}, 100);
}
}
document.getElementById(".animatedTyping").innerHtml = typeThis;
var element = document.createElement('span');
element.innerHTML = typeThis;
typeThis = element.textContent;
type(typeThis, displayText);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<h2><span class="animatedTyping"></span></h2>
答案 0 :(得分:3)
您可以使用Typelt
$('.1').typeIt({
strings: 'This is a simple string.',
speed: 50
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.typeit/4.3.0/typeit.min.js"></script>
<p><span class="1"></span></p>
答案 1 :(得分:1)
jQuery感觉有点矫枉过正。你可以使用普通的javascript来达到同样的效果。只需从您的完整字符串开始,然后在循环中获取它的子字符串并设置超时以再次运行该函数,直到键入整个字符串。要转义HTML编码数据,您可以创建一个新元素,将文本添加为HTML,然后将文本拉出(信用https://stackoverflow.com/a/9609450/1173776) -
var typeThis = "My typing speed is < fast.";
var displayText = "";
function type(fullString, typedSoFar) {
if (fullString.length != typedSoFar.length) {
typedSoFar = fullString.substring(0, typedSoFar.length + 1);
document.getElementById("animatedTyping").innerText = typedSoFar;
setTimeout(function() {
type(fullString, typedSoFar)
}, 100);
}
}
document.getElementById("animatedTyping").innerHtml = typeThis;
var element = document.createElement('span');
element.innerHTML = typeThis;
typeThis = element.textContent;
type(typeThis, displayText);
&#13;
Watch me type -<span id="animatedTyping"></span>
&#13;