简体   繁体   English

jQuery-隐藏特定的div直到单击另一个div,当div悬停时再次隐藏该div

[英]jQuery - Hide a particular div until another is clicked and hide that div again when div is hovered off

Here is what I am trying to do. 这是我想要做的。 I have a button (#facebook-button) that when clicked will show the contents of a div (#facebook). 我有一个按钮(#facebook-button),单击该按钮将显示div(#facebook)的内容。 Now I want it so when the mouse is not on top (hover) of the div #facebook that it then hides the div #facebook. 现在我想要这样,当鼠标不在div #facebook的顶部(悬停)时,它就会隐藏div #facebook。

Here is what I have so far: 这是我到目前为止的内容:

<script type="text/javascript">

jQuery(document).ready(function(){
jQuery('#facebook').hide();

    jQuery('#facebook-button').click(function() {
    jQuery('#facebook').show();
    });

});

</script>

Any suggestions? 有什么建议么?

You can use jQuery's on mouseleave event, that event is fired when the mouse leaves the area. 您可以使用jQuery的mouseleave事件,当鼠标离开该区域时会触发该事件。

<script type="text/javascript">

    jQuery(document).ready(function(){
        jQuery('#facebook').hide().on('mouseleave', function() {
            jQuery('#facebook').hide();
        });

        jQuery('#facebook-button').click(function() {
            jQuery('#facebook').show();
        });

    });

</script>
<script type="text/javascript">

jQuery(document).ready(function(){
    jQuery('#facebook').hide();

    jQuery('#facebook-button').click(function() {
        jQuery('#facebook').show();
        $('#facebook').on('mouseenter', function() {
           // do something or remove that part to just leave mouseleave
        }).on('mouseleave', function(){
              $('#facebook').hide();
        });
    });
});

</script>

Basically after showing the div, we will just spot when his mouse is leaving the #facebook div to hide it. 基本上在显示div之后,我们将发现他的鼠标何时离开#facebook div进行隐藏。 You could also optimize the code and put $('#facebook') in a variable considering the amount of time you re use it. 您还可以优化代码并将$('#facebook')放入变量中,以考虑重新使用它的时间。 Saves you calling jquery more times than actually needed. 节省调用jquery的次数比实际需要的次数更多。

You can try some thing like this. 您可以尝试这样的事情。 CSS CSS

div { display: none; }

HTML HTML

<a id="hover" href="#">Show</a>
<div id="div">Contents</div>

JS JS

$('#hover')
   .mouseleave(function() {
      $('#div').hide();
   })
   .click(function(e) {
        e.preventDefault();

        $('#div').show();
    });

Try this Demo . 试试这个演示

$('.fbContent').hide();
$('button').hover(
    function() {
        $('.fbContent').show();
    },
    function() {
        $('.fbContent').hide();
    }
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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