欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript實(shí)現(xiàn)文字打印機(jī)效果實(shí)例代碼

 更新時(shí)間:2025年06月05日 09:56:30   作者:wuhen_n  
通過(guò)逐字顯示文本,模擬打字機(jī)逐字鍵入的動(dòng)畫(huà)效果,可以廣泛應(yīng)用于對(duì)話(huà)、引導(dǎo)教程和交互式界面中,這篇文章主要介紹了JavaScript實(shí)現(xiàn)文字打印機(jī)效果的相關(guān)資料,需要的朋友可以參考下

前言

文字打印機(jī)效果:通過(guò)逐字顯示文本,模擬打字機(jī)逐字鍵入的動(dòng)畫(huà)效果,可以廣泛應(yīng)用于對(duì)話(huà)、引導(dǎo)教程和交互式界面中。

文字打印機(jī)

文字打印機(jī)主要通過(guò)js控制實(shí)現(xiàn),其核心思想是對(duì)文本字符串進(jìn)行遍歷,每隔一段時(shí)間輸入一個(gè)文字,直到文本字符串遍歷完成;同時(shí)為了保持空格和換行,需要用到 white-space: pre-wrap; 屬性。

代碼實(shí)現(xiàn)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文字打印機(jī)效果</title>
<style>
.hellow-text {
  white-space: pre-wrap; /* 保持空格和換行 */
}
</style>
</head>
<body>
<div class="hellow-text" id="printer"></div>

<script>
document.addEventListener('DOMContentLoaded', function() {
  // 要打印的文本
  const text = "這是一個(gè)文字打印機(jī)效果示例。\n請(qǐng)觀(guān)察文字如何逐個(gè)顯示。"; 
  const printerElement = document.getElementById('printer');
  let index = 0;

  function printText() {
		if (index < text.length) {
			printerElement.textContent += text.charAt(index);
			index++;
			setTimeout(printText, 200); // 每隔200毫秒打印一個(gè)字符
		}
  }
  printText(); // 開(kāi)始打印
});
</script>
</body>
</html>

效果預(yù)覽

文字打印機(jī)效果預(yù)覽

帶光標(biāo)的文字打印機(jī)

上述代碼中,我們實(shí)現(xiàn)了簡(jiǎn)單的文字打印機(jī),現(xiàn)在我們來(lái)為文字添加一個(gè)光標(biāo)效果,讓它更貼合我們實(shí)際的文字打印效果:

代碼實(shí)現(xiàn)

<style>
.hellow-text {
  white-space: pre-wrap; /* 保持空格和換行 */
}
/* 添加光標(biāo)樣式 */
.cursor {
  display: inline-block;
  width: 2px;
  height: 16px;
  background-color: black;
  margin-left: 2px;
	vertical-align: middle; 
  animation: blink 1s step-end infinite;
}
/* 光標(biāo)閃爍動(dòng)畫(huà) */
@keyframes blink {
  50% {opacity: 0;}
}
</style>

<body>
<div class="hellow-text" id="printer"></div>

<script>
document.addEventListener('DOMContentLoaded', function() {
  // 要打印的文本
  const text = "這是一個(gè)文字打印機(jī)效果示例。\n請(qǐng)觀(guān)察文字如何逐個(gè)顯示。"; 
  const printerElement = document.getElementById('printer');
  let index = 0;
	// 創(chuàng)造光標(biāo)屬性span
	let cursorElement = document.createElement('span');
	cursorElement.classList.add('cursor');
  function printText() {
		if (index < text.length) {
			printerElement.textContent += text.charAt(index);
			// 不存在光標(biāo)屬性,則添加
			if (!printerElement.contains(cursorElement)) {
				printerElement.appendChild(cursorElement);
			}
			index++;
			setTimeout(printText, 200); // 每隔200毫秒打印一個(gè)字符
		}
  }

  printText(); // 開(kāi)始打印
});
</script>
</body>

效果預(yù)覽

結(jié)語(yǔ)

通過(guò)本文的介紹,相信你已經(jīng)掌握了如何使用JS實(shí)現(xiàn)文字打印機(jī)效果,希望這些技巧能幫助你提升網(wǎng)頁(yè)設(shè)計(jì)的視覺(jué)效果。

到此這篇關(guān)于JavaScript實(shí)現(xiàn)文字打印機(jī)效果的文章就介紹到這了,更多相關(guān)JS文字打印機(jī)效果內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論