Changing from hover to click?

2019-07-20 10:33发布

问题:

I've recently implemented a small box on my website at the bottom of the page to expand when the mouse hovers over it... This is the code and it all works great.

CSS

#box{
    position:absolute;
    width:300px;
    height:20px;
    left: 33%;
    right: 33%;
    min-width: 32%;
    bottom:0;
    background-color: #353535;
}

javascript

$('#box').hover(function() {
    $(this).animate({
        height: '220px'
    }, 150);
},function() {
    $(this).animate({
        height: '20px'
    }, 500);
});

But I'm curious about how I would go about changing this to open and close on a click rather than the mouse hovering over it?

I've edited it to...

$('#box').click(function() {
    $(this).animate({
        height: '220px'
    }, 150);
},function() {
    $(this).animate({
        height: '20px'
    }, 500);
});

And this works to open the box. But I can't get it to close again with another click.

So close yet so far! :P

回答1:

this should work

$('#box').toggle(function() {
    $(this).animate({
        height: '220px'
    }, 150);
},function() {
    $(this).animate({
        height: '20px'
    }, 500);
});


回答2:

You can probably just use the toggle event handler instead of the click event like so:

$('#box').toggle(function() {...}, function() {...});


回答3:

You can do:

$('#box').click(function() {
  if ($(this).is(':visible')) {
    $(this).hide();
    return;
  }

  $(this).animate({height: '220px'}, 150);
});

On the click, it will hide the element if visible else animate it.