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

JavaScript架子鼓项目中removeTransition函数失效原因排查

JavaScript架子鼓按键样式无法恢复问题排查

我正在开发一个JavaScript架子鼓项目,程序整体运行正常,但按键触发音效和过渡效果后,按键无法恢复初始样式,过渡效果未被移除。编写的removeTransition函数未能生效,用浏览器开发者工具检查发现transitionend未被列为事件监听器,请问原因是什么?

问题代码

function playSound(e) {
    const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
    const key = document.querySelector(`div[data-key="${e.keyCode}"]`);
    if (!audio)
        return;
    key.classList.add('playing');
    audio.currentTime = 0;
    audio.play();
}

function removeTransition(e) {
    if (e.propertyName !== "transform")
        return;
    e.target.classList.remove('playing');
}

window.addEventListener('keydown', playSound);

const keys = Array.from(document.querySelectorAll('.key'));
keys.forEach(key => {
    key.addEventListener('transitionend', removeTransition);
});

原因分析

  1. 语法错误导致事件监听器未绑定:代码中存在大量HTML转义字符("、=>),这些字符在JavaScript中属于非法语法,会导致代码解析失败,后续的transitionend事件绑定逻辑根本没有执行,所以开发者工具里看不到对应的监听器。
  2. 过渡属性判断可能存在遗漏:如果CSS中.playing类的过渡效果涉及多个属性(比如box-shadow、border-color等),transitionend事件会为每个过渡属性单独触发一次,只判断transform属性会导致其他属性触发的事件被忽略,不过这不是当前的核心问题。

解决方案

  1. 修正语法错误:将所有HTML转义字符替换为标准JavaScript语法:
    • 把"替换为普通双引号"
    • 把=>替换为箭头函数符号=>
  2. 可选优化过渡判断:如果CSS过渡了多个属性,可以将判断条件改为if (!e.propertyName.includes('transform')) return;,确保不会错过transform相关的过渡结束事件(部分浏览器可能会返回带前缀的属性名,比如webkitTransform)。

修正后的代码

function playSound(e) {
    const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
    const key = document.querySelector(`div[data-key="${e.keyCode}"]`);
    if (!audio) return;
    key.classList.add('playing');
    audio.currentTime = 0;
    audio.play();
}

function removeTransition(e) {
    // 兼容不同浏览器的属性名前缀
    if (!e.propertyName.includes('transform')) return;
    e.target.classList.remove('playing');
}

window.addEventListener('keydown', playSound);

const keys = Array.from(document.querySelectorAll('.key'));
keys.forEach(key => {
    key.addEventListener('transitionend', removeTransition);
});

内容的提问来源于stack exchange,提问作者Hilda Enyioko

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 16:32:31