简体   繁体   English

在jQuery中切换div的高度

[英]Toggling height of div in jQuery

This question has been already addressed, but none of the solutions have worked for me. 这个问题已经解决,但没有一个解决方案对我有用。

I referred to this earlier question addressing the same problem : 我在前面的问题中提到了同样的问题

I noticed that one of the responses gave this jsfiddle link , which implements the exact functionality that I want, and works. 我注意到其中一个响应给了这个jsfiddle链接 ,它实现了我想要的确切功能,并且有效。

    $("#topbar").toggle(function(){
      $(this).animate({height:40},200);
    },function(){
      $(this).animate({height:10},200);
    });

But when I changed the framework to anything but jQuery 1.4.4, the div starts instantly disappearing as soon as the page loads. 但是当我将框架更改为除jQuery 1.4.4之外的任何内容时,div会在页面加载后立即消失。 This is the problem I've been having on my own project. 这是我在自己的项目中遇到的问题。

Any ideas on how to get that jsfiddle working on jquery 2.x? 关于如何让jsfiddle在jquery 2.x上工作的任何想法? What am I missing? 我错过了什么?

The fix is simple: 修复很简单:

$("#topbar").toggle(function () {
    $(this).animate({
        height: "40px"
    }, 200);
}, function () {
    $(this).animate({
        height: "10px"
    }, 200);
});

You just need to add px units to the height value. 您只需要将px单位添加到高度值。

See demo at: http://jsfiddle.net/audetwebdesign/3dd3s/ 请参阅演示: http//jsfiddle.net/audetwebdesign/3dd3s/

PS PS

Some of the other posted answers show a better way of coding this type of animation. 其他一些已发布的答案显示了一种更好的编码此类动画的方法。 I simply demonstrated how to fix the bug. 我只是演示了如何修复bug。

Note that this use of .toggle has been deprecated since jQuery 1.8. 请注意,从jQuery 1.8开始,不推荐使用.toggle
Reference: http://api.jquery.com/toggle-event/ 参考: http//api.jquery.com/toggle-event/

Why The Unit is Needed 为何需要该单位

Some of the other solutions involve the jQuery .height() function, which returns a unit-less pixel value. 其他一些解决方案涉及jQuery .height()函数,它返回一个无单位像素值。 In this case, the computed value is coerced/cast to be a pixel value, so the 'px` unit is not required. 在这种情况下,计算值被强制/强制转换为像素值,因此不需要'px`单位。

In the original example, the .height() function was not used so the units needed to be specified to make things work. 在原始示例中,未使用.height()函数,因此需要指定单元才能使其工作。

jQuery jQuery的

$("#topbar").click(function () {
    $(this).animate({
        height: ($(this).height() == 40) ? 10 : 40
    }, 200);
});

CSS CSS

#topbar {
    background: orange;
    color: white;
    display:block;
    width:100%;
    text-align:center;
    height:40px;
}

HTML HTML

<div id='topbar'>toggle me</div>

jsFiddle 的jsfiddle

Is this what you're going for? 这是你想要的吗?

http://jsfiddle.net/mmDCk/ http://jsfiddle.net/mmDCk/

$("#topbar").click(function() {
    $(this).animate({
        height: ($(this).height() == 10) ? 40 : 10
    }, 200);
});

That will toggle the height to either 40 or 10 depending on what it is at the moment. 这将根据目前的情况将高度切换到40或10。

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

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