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

设置元素visibility为visible时CSS动画未触发的问题求助

解决点击按钮触发CSS滑入动画的问题

问题原因

你的CSS动画在页面加载时就已经执行完毕了——哪怕元素设置了visibility: hidden,浏览器依然会渲染该元素并运行其动画。当你点击按钮设置visibility: visible时,元素已经处于动画结束的状态(transform: translateY(0)),所以看不到滑入效果。

解决方案:用CSS类控制动画触发

通过给目标元素添加/移除CSS类的方式,让动画仅在点击按钮时才启动,而非页面加载阶段。

修改后的CSS代码

#notification {
  position: fixed;
  z-index: 101;
  bottom: 0;
  transform: translateY(calc(100% + 10px));
  left: 10vw;
  right: 10vw;
  text-align: center;
  height: 20vh;
  overflow: hidden;
  background-color: #ededed;
  color: #000;
  visibility: hidden; /* 初始隐藏,移到CSS统一管理 */
}
@keyframes slideUp {
    0% { transform: translateY(calc(100% + 10px)); }
    100% { transform: translateY(0); }
}
/* 仅当添加此类时,才显示元素并执行动画 */
#notification.show-notification {
    visibility: visible;
    animation: slideUp 2.5s ease forwards;
}

修改后的HTML代码

移除内联的style="visibility: hidden;",统一由CSS控制:

<button id="openNotification">
Open notification
</button>

<div id="notification">
121
</div>

修改后的JavaScript代码

点击按钮时为元素添加动画类:

const feedback = document.getElementById('openNotification');
const notification = document.getElementById("notification");

feedback.addEventListener('click', function (){
  // 避免重复点击重复触发动画
  if (!notification.classList.contains('show-notification')) {
    notification.classList.add('show-notification');
  }
});

补充说明

  • 这种方式逻辑清晰,通过类的切换控制元素状态,符合CSS与JS职责分离的原则。
  • 如果需要支持重复触发(比如关闭后再次打开),可以在关闭时移除show-notification类,下次点击时重新添加即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 03:18:41