基于Typed.js实现文字动效同步切换图片的技术咨询
解决Typed.js文字与图片同步切换的问题
嘿,这问题很好解决!我们可以利用Typed.js自带的回调钩子,在每次文字切换完成时同步更新对应的图片。下面是具体的实现方案:
步骤1:建立文字与图片的对应关系
首先我们把每个Typed.js要展示的字符串,和对应的图片路径一一绑定。用索引对应最稳妥,能避免文字内容修改或空格导致的匹配问题:
// 顺序要和Typed.js的strings数组完全一致 const textImagePairs = [ { imageUrl: "assets/images/hero-section/first-product.png" }, { imageUrl: "assets/images/hero-section/second-product.png" } ];
步骤2:给Typed.js添加切换回调
Typed.js提供了onStringTyped钩子,会在每个字符串输入完成后触发。我们就在这个回调里更新图片,还可以加上平滑过渡效果:
var typed = new Typed('#existing-text', { strings: ["New Text First ", "New Text Second"], backSpeed: 80, typeSpeed: 80, loop: true, startDelay: 100, backDelay: 500, // 字符串输入完成后触发图片切换 onStringTyped: function(index) { const targetImage = document.querySelector('.hero-image'); // 先淡出图片 targetImage.style.opacity = 0; // 延迟后更换图片并淡入 setTimeout(() => { targetImage.src = textImagePairs[index].imageUrl; targetImage.style.opacity = 1; }, 300); }, // 初始化时设置第一张对应图片 onBegin: function() { const targetImage = document.querySelector('.hero-image'); targetImage.src = textImagePairs[0].imageUrl; } });
步骤3:添加CSS过渡动画
为了让图片切换不突兀,给.hero-image加上过渡属性:
.hero-image { transition: opacity 0.3s ease-in-out; /* 和JS里的延迟时间对应 */ opacity: 1; }
完整代码示例
HTML部分
<div class="main hero-box"> <div class="col-xl-7 col-lg-7 col-md-7 col-sm-7 col-xs-12"> <span class="design">We Design</span> <span id="existing-text"></span> </div> <div class="product-image col-xl-5 col-lg-5 col-md-5 col-sm-5 col-xs-12"> <img class="image-replacement hero-image" src="assets/images/hero-section/product-icon.png"/> </div> </div>
JavaScript部分
const textImagePairs = [ { imageUrl: "assets/images/hero-section/first-product.png" }, { imageUrl: "assets/images/hero-section/second-product.png" } ]; var typed = new Typed('#existing-text', { strings: ["New Text First ", "New Text Second"], backSpeed: 80, typeSpeed: 80, loop: true, startDelay: 100, backDelay: 500, onStringTyped: function(index) { const targetImage = document.querySelector('.hero-image'); targetImage.style.opacity = 0; setTimeout(() => { targetImage.src = textImagePairs[index].imageUrl; targetImage.style.opacity = 1; }, 300); }, onBegin: function() { const targetImage = document.querySelector('.hero-image'); targetImage.src = textImagePairs[0].imageUrl; } });
CSS部分
.hero-image { transition: opacity 0.3s ease-in-out; opacity: 1; }
简单说明
onStringTyped的index参数就是当前展示字符串在数组里的位置,我们用它匹配对应的图片路径- 通过修改
opacity配合延迟,实现平滑的淡入淡出切换效果 onBegin钩子确保页面加载时,图片就和初始文字对应上
这样就能实现文字和图片的完美同步切换啦!
内容的提问来源于stack exchange,提问作者psycho developer
相关产品推荐
相关产品推荐

