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

如何点击Start按钮调用setColor函数并避免文本自动变色朗读?

解决点击Start按钮触发逐字变色+音频播放的问题

修复后的完整代码

JavaScript

var mysong = document.getElementById("mysong");
var icon = document.getElementById("icon");

const words = Array.from(document.querySelectorAll(".word, .wordw"));
const speed = 700;
let counter = 0;

const setColor = () => {
  // 避免计数器越界
  if (counter >= words.length) {
    // 重置所有文字颜色和计数器,支持重复触发
    words.forEach(word => word.style.color = "initial");
    counter = 0;
    return;
  }

  // 高亮当前文字
  words[counter].style.color = "#29b4af";
  
  // 其他文字恢复初始颜色
  words.forEach((word, index) => {
    if (index !== counter) {
      word.style.color = "initial";
    }
  });

  counter++;
  setTimeout(setColor, speed);
};

// 合并按钮点击逻辑,同时处理音频和变色
icon.addEventListener('click', function(e) {
  e.preventDefault(); // 阻止a标签默认跳转
  // 重置音频播放进度,确保每次点击从头播放
  mysong.currentTime = 0;
  mysong.play();
  // 重置计数器后触发变色效果
  counter = 0;
  setColor();
});

CSS

body {
  background-image    : url("../imgg/1.jpg");
  background-repeat   : no-repeat;
  background-position : top;
  background-size     : 32.7%;
}

/* 可选:给按钮添加基础样式,增强交互感 */
.start {
  padding: 8px 16px;
  background: #29b4af;
  color: white;
  text-decoration: none;
  border-radius: 4px;
}

HTML

<div class="sayfa1">
  <h1>
    <span class="word">Hello   </span>
    <span class="word"> welcome </span>
    <span class="word">back  </span>
  </h1>
</div>
<div class="but1">
  <a href="#" class="start" id="icon">start</a>
</div>

<audio id="mysong">
  <source src="imgg/bharf.mp3" type="audio/mp3">
</audio>

关键修改说明

  • 移除自动执行的setColor():原代码页面加载后会立刻触发变色,删掉该行后仅在点击按钮时启动效果
  • 合并按钮点击事件:原按钮同时使用onclick属性和icon.onclick绑定,会导致重复触发,现在合并为一个事件处理函数,同时控制音频播放和变色逻辑
  • 修复函数逻辑漏洞:
    • 新增计数器越界判断,避免访问不存在的数组元素
    • 越界后重置所有文字颜色和计数器,支持重复点击按钮触发效果
    • 调整计数器递增时机,避免逻辑混乱
  • 修正拼写错误:将按钮class从satrt改为start,符合语义规范
  • 优化用户体验:阻止a标签默认跳转行为,重置音频播放进度确保每次点击从头播放

内容的提问来源于stack exchange,提问作者Khawla Mirza

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 08:20:26