下载jQuery mouseleave,mouseenter问题

时间:2017-06-23 11:53:51

标签: javascript jquery html css

当我将鼠标悬停在内容区域时,我的下拉超时不会被清除。我不想在悬停时隐藏内容区域。解决这个问题,这次我真的很困惑。 HTML

<button data-drp-hover="mynewid">HOVER</button>
<div class="drp-content" data-drp-content="mynewid">
<span>Item 1</span>
<span>Item 1</span>
<span>Item 1</span>
<span>Item 1</span>
<span>Item 1</span>
</div>

CSS

[data-drp-content] {
display:none;
}
.drp-show[data-drp-content] {
display: block;
}

JS

$("[data-drp-hover]").mouseenter(function () {
    var _drp_x = $(this);
    var _drp_container = $(this).attr("data-drp-hover");
    var _drp_content = $('[data-drp-content="' + _drp_container + '"]');
    _drp_content.addClass("drp-show");
    _drp_content.siblings().removeClass("drp-show");
    $(document).click(function (event) {
        _drp_content.removeClass("drp-show");
    });
    $(_drp_x, _drp_content).click(function (event) {
        event.stopPropagation();
    });
    $(_drp_x, _drp_content).on("mouseleave", function () {
        var timer = setTimeout(function () {
            _drp_content.removeClass("drp-show");
        }, 1000);
        $(_drp_content).on("mouseenter", function () {
            clearTimeout(timer);
        });
    });
});

1 个答案:

答案 0 :(得分:1)

笔:https://codepen.io/anon/pen/GEvEZZ

将var计时器移动到方法的顶部。

// Move the timer to here
var timer;
$("[data-drp-hover]").mouseenter(function () {
    var _drp_x = $(this);
    var _drp_container = $(this).attr("data-drp-hover");
    var _drp_content = $('[data-drp-content="' + _drp_container + '"]');
    _drp_content.addClass("drp-show");
    _drp_content.siblings().removeClass("drp-show");
    $(document).click(function (event) {
        _drp_content.removeClass("drp-show");
    });
    $(_drp_x, _drp_content).click(function (event) {
        event.stopPropagation();
    });
    $(_drp_x, _drp_content).on("mouseout", function () {
        // Should not be var
        timer = setTimeout(function () {
            _drp_content.removeClass("drp-show");
        }, 1000);
        $(_drp_content).on("mouseenter", function () {
            clearTimeout(timer);
        });
    });
});