jQuery Hover on Two Separate Elements

≡放荡痞女 提交于 2019-12-23 03:53:05

问题


I have two separate elements setup which appear on different parts of the DOM - the problem I am facing is that they are absolutely positioned and I can't wrap them in a container div.

I have setup a JSfiddle here - http://jsfiddle.net/sA5C7/1/

What I am trying to do is: move the elements in and out together - so that a user can move their mouse between either element and ONLY once they move off BOTH would it hide again ?

How can I set this up? Because at the moment, once I move off a single element - it fires the "leave event" for that element etc.


回答1:


You could use two boolean variables that you set, each for every element. It gets true when you enter the element and false if you leave.

And only when both are false on leaving => hide the elements.

$(document).ready(function(){
    var bslider = false;
    var btest = false;
    $('#slider').mouseover(function() {
        bslider = true;
        $('#slider, #test').stop(true,false).animate(
                    {'margin-left':'20px'
                    });
    });
    $('#test').mouseover(function() {
        btest = true;
        $('#slider, #test').stop(true,false).animate(
                    {'margin-left':'20px'
                    });
    });
    $('#slider').mouseout(function() {
        bslider = false;
        if(!bslider && !btest)
        {
            $('#slider, #test').stop(true,false).animate(
                    {'margin-left':'0'
                    });
        }
    });
    $('#test').mouseout(function() {
        btest = false;
        if(!bslider && !btest)
        {
            $('#slider, #test').stop(true,false).animate(
                    {'margin-left':'0'
                    });
        }
    });
});



回答2:


The accepted solution works great. To simplify a bit and give an example.

https://jsfiddle.net/ngb1q3kp/2/

$(function(){
    var sliderHover = false;
    var testHover = false;
    $("#slider").hover(function() {
        sliderHover = true;
        doHover();
    }, function() {
        sliderHover = false;
        checkHide();
    });
    $("#test").hover(function() {
        testHover = true;
        doHover();
    }, function() {
        testHover = false;
        checkHide();
    });
    function doHover() {
        $('#slider, #test').stop(true,false).animate({'margin-left':'285px'});
    }
    function checkHide() {
        if (!sliderHover && !testHover) {
            $('#slider, #test').stop(true,false).animate({'margin-left':'0'});
        }
    }
});

If you want a more abstracted example. This can easily handle more than two elements: https://jsfiddle.net/q6o2v8fz/



来源:https://stackoverflow.com/questions/8739108/jquery-hover-on-two-separate-elements

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