技术咨询:如何实现类似gm.graphics网站的文字打字效果及相关类库/自定义代码推荐
嘿,我特意研究过gm.graphics网站的打字动画——那种逐字弹出、偶尔还会删除重打的灵动效果对吧?之前你试了几个类库都没跑起来?没关系,我给你分享两个靠谱方案:一个是用成熟的类库(省心省力),另一个是原生JS自定义实现(灵活无冲突),肯定能解决你的问题!
实现gm.graphics风格打字效果的方案
一、靠谱的第三方类库推荐
1. TypeIt
这个类库轻量且功能齐全,完全能模拟目标网站的打字、删除、循环切换文本的效果,而且兼容性拉满。用法超简单:
先引入它(用CDN最方便),然后写下面的代码:
<!-- HTML容器 --> <span id="type-container"></span> <!-- 引入TypeIt --> <script src="https://cdn.jsdelivr.net/npm/typeit@8.7.1/dist/index.umd.js"></script> <script> // 初始化打字效果 new TypeIt("#type-container", { speed: 100, // 单字打字速度(毫秒) deleteSpeed: 50, // 单字删除速度 loop: true, // 开启循环播放 waitUntilVisible: true // 元素出现在视口才开始动画 }) .type("Hello, this is a typing effect", { delay: 1000 }) // 输入第一句,打完停顿1秒 .pause(500) // 再停顿0.5秒 .delete(4) // 删除最后4个字符 .type("animation!") // 替换成新内容 .pause(1500) // 停顿1.5秒 .delete() // 删除全部内容 .type("Just like gm.graphics!") // 输入新句子 .go(); // 启动动画 </script>
你可以根据目标网站的节奏,调整速度、文本内容和动作序列,完美复刻效果。
2. Typed.js
另一个老牌的打字效果类库,社区支持稳定,用法同样直观,适合快速搭建效果:
<!-- HTML容器 --> <span id="typed"></span> <!-- 引入Typed.js --> <script src="https://cdn.jsdelivr.net/npm/typed.js@2.0.12/lib/typed.min.js"></script> <script> var typed = new Typed('#typed', { strings: ["Hello, typing effect", "Just like gm.graphics", "Customize as you like!"], // 要循环的文本列表 typeSpeed: 80, // 打字速度 backSpeed: 40, // 删除速度 loop: true, // 开启循环 backDelay: 1500 // 删除完成后停顿的时间 }); </script>
它会自动循环切换strings里的文本,打字、删除的节奏都可以自由调整,上手零门槛。
二、原生JS自定义实现(避免类库冲突)
如果之前用类库出问题,大概率是和现有项目代码冲突或者引入方式不对。那用原生JS写一个轻量的自定义函数就最稳妥了,下面这个代码完全模拟目标网站的核心效果:
<!-- HTML容器 --> <span id="custom-type"></span> <script> const typeElement = document.getElementById('custom-type'); // 自定义要展示的文本序列 const textArray = [ "Welcome to gm.graphics style", "Typing effect with JavaScript", "No libraries needed!" ]; let currentTextIndex = 0; let currentCharIndex = 0; let isDeleting = false; const typeSpeed = 120; // 打字速度 const deleteSpeed = 60; // 删除速度 const pauseBetweenTexts = 2000; // 文本切换前的停顿时间 function type() { const currentText = textArray[currentTextIndex]; if (!isDeleting && currentCharIndex < currentText.length) { // 打字阶段:逐字符添加 typeElement.textContent += currentText.charAt(currentCharIndex); currentCharIndex++; setTimeout(type, typeSpeed); } else if (isDeleting && currentCharIndex > 0) { // 删除阶段:逐字符删除 typeElement.textContent = currentText.substring(0, currentCharIndex - 1); currentCharIndex--; setTimeout(type, deleteSpeed); } else { // 切换文本:切换状态,准备下一轮 isDeleting = !isDeleting; if (!isDeleting) { currentTextIndex = (currentTextIndex + 1) % textArray.length; // 循环切换文本 } setTimeout(type, pauseBetweenTexts); } } // 启动打字效果 type(); </script>
如果想要加上目标网站的光标闪烁效果,再加几行CSS就行:
#custom-type::after { content: "|"; animation: blink 1s infinite; } @keyframes blink { 0%, 50% { opacity: 1; } 51%, 100% { opacity: 0; } }
这个自定义方案完全没有外部依赖,你可以直接嵌入项目,还能根据需求随意修改参数,再也不用担心类库冲突问题。
如果之前类库不能运行,你可以检查下:是不是CDN链接失效了?是不是元素选择器写错了?或者有没有和项目里的其他JS代码冲突?换上面的方案试试,肯定能行!
内容的提问来源于stack exchange,提问作者Paresh Nandaniya
相关产品推荐
相关产品推荐

