开发者

jQuery - how to listen for the mouse leaving an area of the screen

In the application I'm working on, I use span tags in long paragraphs to provide both:

  • A clickable link, handled with Javascript, and

  • On mouseover, an "edit this" button displayed to the side of the link (with different functionality from the click).

Placing and showing the "edit this" button on mouseover is relatively easy. What I'm trying to figure out is, how ca开发者_如何学Pythonn I properly hide the button on mouseleave?

See my working example: http://jsfiddle.net/nrabinowitz/6uKk8/4/

The problem:

  • I can't just use the mouseleave event on the span, because that would hide the button before it can be clicked.

  • I can't use a transparent div sized to include both the span and the button, because if the div is above the span, it blocks the click event, and if I use the z-index to place the div below the paragraph, it doesn't seem to receive the mouseleave event at all.

I could probably cludge something together with mousemove on the entire paragraph, but that seems really ugly. I don't think I can use some kind of coordinated event handling to check mouseleave on both the span and the button, because there's space between them.

My desired behavior is to have a (DOM-based or calculated) invisible box that includes both the span and the button, and to listen for the mouse leaving that box, at which time I can hide the button. What's the right way to do this?


You could put the hiding on a timer and start the timer when the mouse leaves your <span>:

var timer = null;
$('span.editable').mouseleave(function() {
    if(timer)
        clearTimeout(timer);
    timer = setTimeout(function() {
        $('#edit-this').hide();
        timer = null;
    }, 2000);
});

And then cancel the timer when the mouse enters #edit-this and set up a one-time event handler to hide #edit-this when the mouse leaves it:

$('#edit-this').mouseover(function() {
    if(timer)
        clearTimeout(timer);
    timer = null;

    var $this = $(this);
    $this.one('mouseleave', function() {
        $this.hide();
    });
});

You'll also want to clear the timer in your mouseover for the span (thanks for catching this):

$('span.editable').mouseover(function(e) {
    if(timer)
        clearTimeout(timer);
    timer = null;
    // ...
});

Demo: http://jsfiddle.net/ambiguous/pBtG8/2/


If all you want is edit this to show until they mouseout of edit-this, this code will do the trick:

$('div.#edit-this').mouseleave(function(){
    $('#edit-this').hide();
});

http://jsfiddle.net/MarkKramer/6uKk8/12/

Also, I set it to use the jQuery timers plugin so when you scroll over, a timer will start and if the edit this button isn't scrolled over after two seconds, it will hide itself.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜