prevent datepicker from triggering parent mouselea

2019-07-15 10:10发布

I display an abolute div with a jQuery $.animate({height: 'toggle', opacity: 'toggle'}) on a jQuery $.hover().

I have a jQuery UI datepicker attached to a div within the aforementioned absolute div with changeMonth: true and changeYear: true.

When a month or year are changed or a date is selected the animation fires.

How can I prevent the month/year change & date selection from triggering the $.hover()?

http://jsfiddle.net/e3zP2/

html

<div id="hoverAnchor">hover me</div>
<div id="hoverMe" style="display:none">
    arbitrary text
    <div id="dateSelector"></div>
</div>

js

$(document).ready(function () {

    $("#dateSelector").datepicker({
        changeMonth: true,
        changeYear: true
    });

    $("#hoverAnchor").add($("#hoverMe")).hover(function(){
        $("#hoverMe").stop(true,false).animate({
            height: 'toggle',
            opacity: 'toggle'
        }, 200);
    });

});

1条回答
混吃等死
2楼-- · 2019-07-15 10:26

You need to do a couple things in order for this to work properly.

First, you need to wrap the HTML in a div to act as the container:

HTML:

<div id="container">
    <div id="hoverAnchor">hover me</div>
    <div id="hoverMe" style="display:none">arbitrary text
        <div id="dateSelector"></div>
    </div>
</div>

Next, rather than using .hover() (which can sometimes be unreliable), I recommend using .mouseenter() along with .mouseleave(). Also use a var to hold boolean of whether datepicker open/closed. The reason for this boolean is due to the input. On click, a second .mouseenter() event will be called, so without it, #hoverme would toggle a second time.

$(document).ready(function () {
    $("#dateSelector").datepicker({
        changeMonth: true,
        changeYear: true
    });
    var _enter = false;
    $("#container").add(
    $("#container")).mouseenter(function () {
        if (!_enter) {
            $("#hoverMe").stop(true, false).animate({
                height: 'toggle',
                opacity: 'toggle'
            }, 200);
        }
        _enter = true;
    }).mouseleave(function () {
        _enter = false;
        $("#hoverMe").stop(true, false).animate({
            height: 'toggle',
            opacity: 'toggle'
        }, 200);
    });
});

DEMO: http://jsfiddle.net/dirtyd77/e3zP2/18/

Hope this helps!

查看更多
登录 后发表回答