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>
添加回答
舉報