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

HTML/CSS/JS通知组件异常:点击后通知框无法重置消失

问题分析与解决方案

你的通知组件存在两个核心问题:

  1. 初始状态未设置隐藏,且slideIn类从未被移除,导致动画结束后元素停留在可视区域
  2. 重复点击按钮时,之前的定时器仍在运行,新旧动画冲突,无法正确重置状态

修复步骤:

1. 调整CSS初始状态

给通知容器添加初始隐藏样式,确保页面加载时它在屏幕外:

.nofitication_area_gonderen{
    position: absolute;
    width: 341px;
    height: 83px;
    top: 48px;
    left: 790px;
    flex-shrink: 0;
    background: rgba(19, 20, 20, 0.76);
    /* 添加以下两行 */
    transform: translateY(-100%);
    visibility: hidden;
}

2. 重写JavaScript逻辑

每次调用Notify时重置所有状态,清除之前的定时器,避免动画冲突:

// 全局存储定时器ID,用于清除
let notifyTimer = null;
let slideOutTimer = null;

function Notify(NotifyTime) {
    const myElement = document.getElementById('nofitication_area_gonderen');
    const labelElement = document.getElementById("nofitication_area_gonderen_label");

    // 清除之前的所有定时器,重置状态
    clearTimeout(notifyTimer);
    clearTimeout(slideOutTimer);
    myElement.classList.remove('slideIn', 'slideOutUp');

    // 设置通知内容
    labelElement.innerHTML = '<span> Test <span style="color: yellow;"> Notify </span> </span>';

    // 触发滑入动画
    myElement.style.visibility = 'visible';
    myElement.classList.add('slideIn');

    // 监听滑入动画结束,移除slideIn类
    const handleSlideInEnd = () => {
        myElement.classList.remove('slideIn');
        myElement.removeEventListener('animationend', handleSlideInEnd);
    };
    myElement.addEventListener('animationend', handleSlideInEnd);

    // 设置自动滑出定时器
    notifyTimer = setTimeout(() => {
        myElement.classList.add('slideOutUp');
        // 滑出动画结束后重置状态
        slideOutTimer = setTimeout(() => {
            myElement.classList.remove('slideOutUp');
            myElement.style.visibility = 'hidden';
            myElement.style.transform = 'translateY(-100%)';
        }, 400);
    }, NotifyTime);
}

document.getElementById("click_btn").addEventListener("click",function() {
    Notify(2500)
});

3. 优化动画细节

统一slideOutUp动画的transform值,避免浏览器兼容问题:

@keyframes slideOutUp {
    0% {
        transform: translateY(0);
    }
    100% {
        visibility: hidden;
        transform: translateY(-100%);
    }
}

效果说明

  • 点击按钮时,通知框会从上方滑入,停留2.5秒后滑出隐藏
  • 重复点击按钮时,当前的通知会立即重置,重新开始滑入-停留-滑出的流程
  • 动画结束后元素会回到初始隐藏状态,不会停留在屏幕上

内容的提问来源于stack exchange,提问作者Mehmet Akgün

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 12:21:29