You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何自定义输入框打字机效果?如何用CSS隐藏输入框闪烁光标?

自定义输入框打字机效果及隐藏光标方案

一、自定义输入框的打字机效果

输入框的打字机效果需要结合JavaScript控制文本的逐字符输入逻辑,可按需调整打字速度、循环逻辑甚至添加回退重打效果,以下是两种常用实现:

基础逐字输入效果

适合按固定文本顺序逐个字符填入输入框的场景:

<input type="text" id="basic-typewriter" readonly>
<script>
const input = document.getElementById('basic-typewriter');
const targetText = "这里是打字机效果的演示文本";
let charPos = 0;
const typeInterval = 150; // 每字符输入间隔(毫秒)

function typeCharacter() {
  if (charPos < targetText.length) {
    input.value += targetText[charPos];
    charPos++;
    setTimeout(typeCharacter, typeInterval);
  }
}

// 页面加载完成后启动效果
window.onload = typeCharacter;
</script>

带回退修正的进阶效果

模拟输入错误后删除重打的真实打字场景:

<input type="text" id="advanced-typewriter" readonly>
<script>
const input = document.getElementById('advanced-typewriter');
const textList = [
  "尝试输入一段错误内容",
  "修正为正确的演示文本"
];
let listIndex = 0;
let charIndex = 0;
let isDeleting = false;
const typeSpeed = 120;
const deleteSpeed = 80;

function typeCycle() {
  const currentText = textList[listIndex];
  
  if (!isDeleting && charIndex < currentText.length) {
    input.value += currentText[charIndex];
    charIndex++;
    setTimeout(typeCycle, typeSpeed);
  } else if (isDeleting && charIndex > 0) {
    input.value = input.value.slice(0, -1);
    charIndex--;
    setTimeout(typeCycle, deleteSpeed);
  } else if (!isDeleting && charIndex === currentText.length) {
    // 输入完成后停留1.5秒再开始删除
    setTimeout(() => {
      isDeleting = true;
      typeCycle();
    }, 1500);
  } else {
    isDeleting = false;
    listIndex = (listIndex + 1) % textList.length;
    setTimeout(typeCycle, 500);
  }
}

window.onload = typeCycle;
</script>

二、隐藏输入框的闪烁光标

通过CSS可以轻松隐藏输入框的默认闪烁光标,以下是几种可靠方案:

方案1:直接设置光标为透明(推荐)

利用caret-color属性将光标颜色设为透明,不影响文本显示:

#basic-typewriter, #advanced-typewriter {
  caret-color: transparent;
}

方案2:兼容旧浏览器的文本偏移法

针对不支持caret-color的旧浏览器,通过color和text-shadow让文本正常显示的同时隐藏光标:

#basic-typewriter {
  color: transparent;
  text-shadow: 0 0 0 #333; /* #333为文本实际颜色 */
}

方案3:只读输入框的光标禁用

如果输入框是只读状态,可添加pointer-events: none防止点击触发光标,配合透明光标使用:

#basic-typewriter {
  caret-color: transparent;
  pointer-events: none;
}

内容的提问来源于stack exchange,提问作者Hai Alaluf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 20:12:48