jquery addclass removeclass的时候,transistion无效,如何解决?

.hide {
        transition: all 1s;
        -webkit-transition: all 1s;
        display: none;
    }

    #bg-mask {
        transition: all 1s;
        -webkit-transition: all 1s;
        backdrop-filter: blur(6px);
        position: fixed;
        left: 0;
        top: 0;
        bottom: 0;
        right: 0;
        background-color: black;
        opacity: 0.5;
    }


    $(function () {
        $("#couponText").click(function (e) {
            $('#popup').removeClass('hide')
            $("#bg-mask").removeClass("hide")
            e.stopPropagation()
        })
        $("#dialogClose").click(function () {
            $('#popup').addClass('hide')
        })
        document.body.onclick = function closePopup(e) {
            if (!$("#popup").hasClass("hide") && !$(e.target).closest($('#popup')).length) {
                $("#popup").addClass("hide")
                $("#bg-mask").addClass("hide")
                $(document).unbind('click', closePopup);
            }
        }
    })
阅读 1.6k
1 个回答

因为 .hide 把元素直接 display:none 了,就不会触发 opacity 属性的渐变了。
你得把 display:none 修改成 opacity:0 才行。
最后动画执行完毕再去把 #bg-mask 设置为 display:none

中间可能会造成背景元素无法点击,所以可以同时再 .hide 类上添加 pointer-events: none 属性使点击效果穿透。


说个题外话,既然你已经使用了 jQuery 那么可以使用 jQuery 提供的 .fadeIn().fadeOut() 两个方法来做渐入显隐。


本文参与了SegmentFault 思否面试闯关挑战赛,欢迎正在阅读的你也加入。
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题