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

网站通知删除后其余通知平滑过渡效果实现求助

实现通知删除后的平滑过渡效果

要解决删除通知时剩余通知直接跳转的问题,核心是给通知元素添加过渡动画,让元素先平滑消失,再从DOM中移除,同时让容器的布局变化也有平滑过渡。以下是具体修改方案:

1. 添加CSS过渡样式

给.notifications容器和.notification元素添加过渡属性,确保布局变化和元素消失都有平滑效果:

.notifications {
  display: flex;
  flex-direction: column;
  gap: 12px; /* 通知之间的间距,确保过渡时间距变化也平滑 */
  transition: all 0.3s ease;
}

.notification {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  padding: 12px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  /* 添加过渡属性,控制元素消失的动画 */
  opacity: 1;
  transform: translateY(0);
  transition: opacity 0.3s ease, transform 0.3s ease, height 0.3s ease;
  overflow: hidden;
}

/* 定义移除时的样式 */
.notification.remove {
  opacity: 0;
  transform: translateY(-20px);
  height: 0;
  padding: 0 12px;
  margin: 0;
}

2. 修改JavaScript逻辑

不再直接删除元素,而是先给通知添加remove类触发过渡动画,等动画结束后再从DOM中移除:

var notification_max = 5;
function notification(title, content, type){
  if(document.querySelectorAll('.notification').length >= notification_max) return
  function icon(){
    if(type == 'error') return '<i class="fal fa-exclamation-triangle"></i>'
    if(type == 'message') return '<i class="fas fa-comment-alt-dots"></i>'
  }
  var htmlContent = `
      <div class="icon">
        ${icon()}
      </div>
      <div class="text">
        <div class="title">${title}</div>
        <div class="content">${content}</div>
      </div>
  `
  var newNotification = document.createElement('div')
  newNotification.classList.add("notification")
  newNotification.innerHTML = htmlContent
  
  document.querySelector(".notifications").appendChild(newNotification)
  
  window.setTimeout(()=>{
    // 添加移除类触发动画
    newNotification.classList.add('remove');
    // 监听动画结束事件,完成后删除元素
    newNotification.addEventListener('transitionend', function() {
      if (this.classList.contains('remove')) {
        this.remove();
      }
    }, { once: true }); // once确保只触发一次
  },2000)
}

notification("Title", "Content", "error")

关键说明

  • 通过给.notification添加remove类,让元素逐渐透明、向上移动并收缩高度,同时.notifications的gap过渡会让剩余通知平滑移动到新位置
  • 使用transitionend事件确保动画完全结束后再删除元素,避免布局突变
  • 调整notification_max的判断为>=,避免超过最大数量的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 03:54:28