简体   繁体   中英

Hide a div on hover outside of div

<div id='container'>
    <div id="animate"></div>
</div>

I have a small div inside a big div with id container . i want to hide div with id animate if someone hovers the out side of small div . it should remain open when mouse is over the small div .

This should do it

$('#small').hover(function () {
    $('#animate').show();
}, function () {
    $('#animate').hide();
});

Try:

CSS:

#container{width:100px;height:100px;background:#F00;}
#animate{width:50px;height:50px;background:#0F0;}

Script:

$(function(){
    $('#container').mouseenter(function(){
        $('#animate').fadeTo(1000,0)
                     .mouseenter(function(){$(this).fadeTo(1000,1)});
    }); // use 750 in place of 1000 to animate it fast
});

Docs http://api.jquery.com/mouseenter/

HTML:

<div id='container'>
    <div id="animate">&nbsp;</div>
</div>

Fiddle: http://jsfiddle.net/aZmfz/4/

HTML:

<div id='container'>
    <div id="animate">HI!</div>
</div>

CSS:

#container{
    width: 100px;
    height: 200px;
    background-color: black; 
}
#animate{
    height: 50px;
    width: 100px;
    background-color: white;
    opacity: 0;
}

jQuery:

$("#animate").hover(
    function(){
        $(this).stop().animate({
            opacity: 1
        }, 1000);
    },
    function(){
        $(this).stop().animate({
            opacity: 0
        }, 1000);
    }
);

EXAMPLE

You may not want to do a strict show / hide , because the element will have no height/width to hover over when it's hidden . Instead, you may prefer to set the opacity to 0 (to hide) or 1 (to show) and let the animate function transition between the two. You'll also notice that I used the .stop() function. This is because if you hover back and forth over the element it will continue to call the queued up animations. Calling stop first will prevent this.

You can achieve the same effect with pure CSS:

#animate {
    -webkit-transition: opacity 0.2s;
    -moz-transition: opacity 0.2s;
    transition: opacity 0.2s;
}

#container:hover #animate {
    opacity: 0;
}

#container #animate:hover {
    opacity: 1;
}

Demo: http://jsfiddle.net/gXz2A/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM