prevent datepicker from triggering parent mouseleave

▼魔方 西西 提交于 2019-12-11 01:25:47

问题


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:


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!



来源:https://stackoverflow.com/questions/16195454/prevent-datepicker-from-triggering-parent-mouseleave

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!