Changing from hover to click?

给你一囗甜甜゛ 提交于 2019-12-12 17:36:37

问题


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.



来源:https://stackoverflow.com/questions/4943886/changing-from-hover-to-click

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