单击元素时Div逐渐消失

时间:2019-03-26 15:10:26

标签: jquery

我有多个链接,单击链接时弹出按钮会淡入,每个链接都有弹出按钮,再次单击时弹出按钮会淡出。但是,当需要隐藏/不可见时,弹出控件会逐渐消失。

我已经走了很远,但是我只需要一点推动力,我就无法弄清缺少了什么。

如何再次单击弹出的相应链接以隐藏弹出框,使其保持隐藏状态/不可见?

EXEC [dynamic_partitions] @ID='2015';
//Variables
var trigger = $(".trigger");
var flyout = $(".flyout");
var close = $(".close-btn");

$(function() {
  $(trigger).click(function(e) {
    //Hide any other flyout that's visible
    $(this).parents().find(flyout).fadeOut("fast");

    //Toggle active class
    $(this).next(flyout).toggleClass("is-active");

    //Display/hide an actual flyout
    $(this).next(flyout).fadeToggle("fast");

    e.stopPropagation();
  });

  //Fade out the flyout when clicking on the Close button
  $(close).click(function(e) {
    $(this).parent(flyout).fadeToggle("fast").removeClass("is-active");
    e.stopPropagation();
  });

  //Fade out the flyout when clicking anywhere on the page
  $(document).click(function(e) {
    if ($(e.target).closest(flyout).length === 0) {
      $(flyout).fadeOut("fast", function() {
        //Remove class after animation is finished
        $(this).removeClass("is-active");
      });
    }
  });

  //Fade out the flyout when pressing the ESC key
  $(document).keydown(function(e) {
    if (e.keyCode === 27) {
      $(flyout).fadeOut("fast", function() {
        //Remove class after animation is finished
        $(this).removeClass("is-active");
      });
    }
  });
});
.flyout {
  display: none;
  padding: 20px;
  position: relative;
  background: #eee;
}

.close-btn {
  display: flex;
  width: 20px;
  height: 20px;
  justify-content: center;
  align-items: center;
  border-radius: 100px;
  position: absolute;
  top: 5px;
  right: 5px;
  text-decoration: none;
  background: #999;
  color: white;
}

.is-active {
  box-shadow: 0 0 0 1px red;
}


/*Styles not needed for demo*/

.flyout-module {
  float: left;
  width: 200px;
  margin-right: 10px;
  overflow: visible;
}

p {
  margin: 0;
}

这是一个小提琴:https://jsfiddle.net/rzea/hn9cdf34/25/

谢谢。

1 个答案:

答案 0 :(得分:0)

我解决了这个问题。

这是正确“遍历” DOM的问题。

如上所述,我需要将trigger元素“移出”到其父容器中,然后寻找该容器的兄弟姐妹,然后在内部寻找浮空并将其淡出。

解决方法是

//Hide any other flyout that's visible
$(this).parent().siblings().find(flyout).fadeOut("fast", function(){
    //Remove class after animation is finished
  $(this).removeClass("is-active");
}); 

无效的旧行看起来像这样(仅供参考):

$(this).parents().find(flyout).fadeOut("fast");

这是固定的小提琴:https://jsfiddle.net/rzea/hn9cdf34/37/

感谢@camainc,他的回答启发了我提出解决方案:)