当悬停子元素时,JQuery在mouseleave上重复mouseenter事件

时间:2018-01-28 06:17:05

标签: javascript jquery

遇到以下代码问题。将鼠标悬停在帮助图标上,然后将鼠标移到右侧,事件将多次触发,并且跨越"橡皮筋"上和下。关于如何缓解这个问题的建议?

HTML

<div class="help">?<span>Help text.</span></div>

CSS(SCSS)

div.help {
  position: relative;
  margin-right: 8px;
  bottom: 1px;
  box-sizing: border-box;
  cursor: pointer;
  font-size: 14px;
  display: inline-block;
  text-align: center;
  line-height: 14px;
  width: 16px;
  height: 16px;
  color: white;
  font-weight: bold;
  background-color: blue;
  border-radius: 8px;
  transition: all 0.25s ease;
  z-index: 5;
  &:hover {
    background-color: orange;
  }
  > span {
    text-align: left;
    position: absolute;
    display: none;
    min-width: 300px;
    top: 0;
    left: 20px;
    font-weight: normal;
    padding: 15px;
    background-color: orange;
    border-radius: 8px;
  }
}

JS(JQuery)

$(document).ready(function() {
  $(".help").mouseenter(function() {
    $(this).find("span").show("fast");
  }).mouseleave(function() {
    $(this).find("span").slideUp("fast");
  });
});

我试过了:

$(".help span").mouseenter(function() {
  event.preventDefault();
});

// In mouseenter event:
// event.stopPropagation();

在这里尝试一下:

https://codepen.io/sorensend/pen/VQZzxO

1 个答案:

答案 0 :(得分:1)

试试这个:

$(document).ready(function() {
    $(".help").mouseenter(function() {
        $(this).find("span").show("fast");
    }).mouseleave(function() {
        $(this).find("span").slideUp("fast");
    });

    $(".help span").mouseleave(function(event) {
        event.stopPropagation();
    });

    $(".help span").mouseenter(function(event) {
        event.stopPropagation();
    });
});

示例:https://codepen.io/anon/pen/oEvGNK