3 回答
TA贡献1874条经验 获得超12个赞
你完成了几乎所有的工作,你错过的是你必须选择你想要修改的元素:
创建一个
<p>
(或任何其他标签,没有限制)添加一个
id
标签在你的js中选择标签
document.getElementById()
将代码段中的每个实例替换
document.body
为所选元素
我删除了它,因为它什么也setTimeout
没给 imo,如果您的情况需要,请随时将其添加var
回去let
const element = document.getElementById("typed")
let str = element.innerHTML;
let i = 0;
element.innerHTML = "";
let se = setInterval(function() {
i++;
element.innerHTML = str.slice(0, i) + "|";
if (i == str.length) {
clearInterval(se);
element.innerHTML = str;
}
}, 100);
// I slowed the interval to make it more visible it only type the center element
text shown everytime
<p id="typed">
this text will be typed
</p>
this text shown everytime too
如果需要,第二个代码段允许您在同一页面中输入多个消息
const elements = document.getElementsByClassName("typed")
Array.from(elements).forEach(el => {
let str = el.innerHTML;
let i = 0;
el.innerHTML = "";
let se = setInterval(function() {
i++;
el.innerHTML = str.slice(0, i) + "|";
if (i == str.length) {
clearInterval(se);
el.innerHTML = str;
}
}, 100);
})
text shown everytime
<p class="typed">
this text will be typed
</p>
this text shown everytime too
<p class="typed">
this text will be typed too
</p>
TA贡献1859条经验 获得超6个赞
首先为需要打字效果的元素添加ID属性。
var str = document.getElementById("heading").innerHTML.toString();
var i = 0;
document.getElementById("heading").innerHTML = "";
setTimeout(function() {
var se = setInterval(function() {
i++;
document.getElementById("heading").innerHTML = str.slice(0, i) + "|";
if (i == str.length) {
clearInterval(se);
document.getElementById("heading").innerHTML = str;
}
}, 10);
});
<html>
<body>
Text without typing effect
<p id="heading">Text with typing effect</p>
</body>
</html>
TA贡献1810条经验 获得超5个赞
你只需要getElementById
和 两个span
s,为了让它有点真实,一个模拟光标的动画。
如果您愿意,她是更高级的代码。
let span = document.getElementById( 'typewriter')
const text = 'How are you today?';
const length = text.length;
span.innerText = '';
let index = 0;
let se = setInterval(function() {
span.innerText = text.slice(0, index);
if (index++ == text.length) {
clearInterval(se);
span.innerText = text.slice(0, index);
}
}, 100);
#cursor {
white-space: pre;
background-color: #f00;
animation-name: cursor;
animation-duration: 1s;
animation-timing-function: cubic-bezier(0, 1, 0, 1);
animation-delay: 0s;
animation-iteration-count: infinite;
animation-direction: normal;
animation-fill-mode: none;
animation-play-state: running;
}
@keyframes cursor {
0% { opacity: 1; }
50% { opacity: 0; }
100% { opacity: 1; }
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=">
<title></title>
</head>
<body>
<span id='typewriter'></span>
<span id='cursor'>_</span>
</body>
</html>
添加回答
举报