亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

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

前言

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

文字打印機

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

代碼實現(xiàn)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文字打印機效果</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 = "這是一個文字打印機效果示例。\n請觀察文字如何逐個顯示。"; 
  const printerElement = document.getElementById('printer');
  let index = 0;

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

效果預(yù)覽

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

帶光標的文字打印機

上述代碼中,我們實現(xiàn)了簡單的文字打印機,現(xiàn)在我們來為文字添加一個光標效果,讓它更貼合我們實際的文字打印效果:

代碼實現(xiàn)

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

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

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

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

效果預(yù)覽

結(jié)語

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

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

相關(guān)文章

最新評論