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

原生JS点击Modal时Sketch动画未触发,求解决方法

我帮你梳理了代码里的几个核心问题,这应该就是动画没触发的根源:

1. CSS选择器混淆:ID与类的误用

你在JS里是给#modal-container添加类(classList.add(buttonId)),但CSS里写的是#modal-container#sketch——这是在匹配同时拥有modal-container和sketch两个ID的元素,而一个元素只能有一个ID,所以这些样式根本不会生效。

你需要把所有CSS中#modal-container#sketch的选择器,替换成类选择器#modal-container.sketch,比如:

// 原错误写法
#modal-container#sketch { transform: scale(1); }
// 修改后
#modal-container.sketch { transform: scale(1); }

所有涉及#modal-container#sketch的规则都要做这个替换,这样当JS给容器加上sketch类时,动画样式才能被正确应用。

2. SVG矩形缺少描边属性

你的SVG <rect>标签只有fill="none",但原示例里的矩形是带有stroke(描边颜色)和stroke-width(描边宽度)属性的。没有这些属性,sketchIn/sketchOut动画的stroke-dashoffset变化根本不会有视觉效果。修改HTML里的rect:

<rect x="0" y="0" fill="none" width="226" height="162" rx="3" ry="3" stroke="#fff" stroke-width="2"></rect>

这样描边才会显示,sketch动画的绘制效果才能正常呈现。

3. 关闭动画触发对象错误

你在关闭按钮的事件里给按钮本身加了out类:this.classList.add("out");,但CSS里的关闭动画是给#modal-container.out设置的。正确的做法是把out类加到模态容器上,而不是按钮:

// 替换原来的 this.classList.add("out");
const modalContainer = document.querySelector("#modal-container");
modalContainer.classList.add("out");

// 动画结束后记得清理类,避免影响下次打开
setTimeout(() => {
  modalContainer.classList.remove("sketch", "out");
}, 500); // 等待动画时长(0.5s)后移除类

4. 动画层级与冲突修复

你CSS里给.modal同时设置了modalFadeIn(背景色动画)和modalContentFadeIn(透明度+位置动画),这会导致动画冲突。原示例中,modalContentFadeIn是针对模态框内的内容(比如文本、按钮)的,不是模态框本身。调整CSS规则:

// 替换原有的模态内容动画规则
#modal-container.sketch .modal-background .modal > *:not(.modal-svg) {
  opacity: 0;
  position: relative;
  animation: modalContentFadeIn 0.5s 1s cubic-bezier(0.165, 0.84, 0.44, 1) forwards;
}

// 对应的关闭动画也要调整
#modal-container.sketch.out .modal-background .modal > *:not(.modal-svg) {
  animation: modalContentFadeOut 0.5s cubic-bezier(0.165, 0.84, 0.44, 1) forwards;
}

做完这些修改后,你的Sketch动画应该就能正常触发了。另外要确保你的buttonId值确实是sketch,不然类名不匹配也不会生效哦~

内容的提问来源于stack exchange,提问作者Mégane Londoño

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:05:24