简体   繁体   English

从悬停更改为点击?

[英]Changing from hover to click?

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 CSS

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

javascript 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 :P

您可能只需要使用toggle事件处理程序,而不是click事件,如下所示:

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

this should work 这应该工作

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

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. 单击时,它将隐藏该元素(如果可见),否则将对其进行动画处理。

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

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