当前位置: 动力学知识库 > 问答 > 编程问答 >

jquery - prevent datepicker from triggering parent mouseleave

问题描述:

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);

});

});

网友答案:

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!

分享给朋友:
您可能感兴趣的文章:
随机阅读: