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

求助:JavaScript实现Div开关动画及点击外部关闭问题

JavaScript问题解决方案

问题1:实现div隐藏时的动画效果

当前代码直接通过toggle("fo")切换显示状态,但.fo类包含display: none,导致元素立刻消失,隐藏动画无法触发。解决思路是分离显示状态控制与动画逻辑:播放隐藏动画后再设置display: none;显示时先恢复display: block,再触发显示动画。

修改后的CSS

/* 基础遮罩层样式,默认隐藏 */
.fo {
  position: fixed;
  margin-left: auto;
  margin-right: auto;
  width: 100%;
  height: 100%;
  display: none;
}
/* 显示动画类 */
.fo-show {
  animation: ani 0.5s ease forwards;
}
/* 隐藏动画类 */
.fo-hide {
  animation: ani2 0.5s ease forwards;
}
.btn-form-close {
    border: 0;
    font-size: 3rem;
    position: absolute;
    top: -2%;
    width: 0;
    height: 0;
    right: 10%;
    line-height: normal;
    cursor: pointer;
}
@keyframes ani {
    0% {
        transform: translateX(-850px);
    }
    100%{
        transform: translateX(0px);
    }
}
@keyframes ani2 {
    0% {
        transform: translateX(0px);
    }
    100%{
        transform: translateX(850px);
    }
}

问题2:点击外部区域关闭div

给document绑定点击事件,判断点击目标是否属于遮罩层内部或打开按钮,若都不属于则关闭遮罩;同时阻止遮罩层内部的点击事件冒泡,避免误触发外部关闭逻辑。

完整修改后的JS代码

const btnClose = document.getElementById('btn-close');
const fo = document.getElementById('fo');
const openBtns = document.querySelectorAll('.but-oferts');

// 显示遮罩
function showFo() {
  fo.style.display = 'block';
  fo.classList.remove('fo-hide');
  fo.classList.add('fo-show');
}

// 隐藏遮罩(等待动画结束后再隐藏)
function hideFo() {
  fo.classList.remove('fo-show');
  fo.classList.add('fo-hide');
  fo.addEventListener('animationend', function handleEnd() {
    fo.style.display = 'none';
    fo.removeEventListener('animationend', handleEnd);
  }, { once: true });
}

// 绑定所有打开按钮事件
openBtns.forEach(btn => btn.addEventListener('click', showFo));

// 绑定关闭按钮事件
btnClose.addEventListener('click', hideFo);

// 点击外部关闭遮罩
document.addEventListener('click', function(e) {
  const isFoInner = fo.contains(e.target);
  const isOpenBtn = Array.from(openBtns).some(btn => btn.contains(e.target));
  if (!isFoInner && !isOpenBtn && fo.style.display !== 'none') {
    hideFo();
  }
});

// 阻止遮罩内部点击冒泡
fo.addEventListener('click', e => e.stopPropagation());

修改后的HTML(结构不变,仅补全闭合标签)

<div id="fo" class="fo">
  <div style="background-color: #000; transform: translate(50%,30%); border-radius: 30px; height: 70%; width: 50%;">
    <button id="btn-close" style="border: 0; background-color: #000; margin-top: 2%; font-size: 3rem; color: white; float: right;">
      <span class="btn-form-close">&times;</span>
    </button>
  </div>
</div>
<button id="btnk" class="but-oferts">Otworz</button>
<button id="btnk1" class="but-oferts">Otworz</button>
<button id="btnk2" class="but-oferts">Otworz</button>
<button id="btnk3" class="but-oferts">Otworz</button>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 01:32:48