在jQuery中切换div的高度 [英] Toggling height of div in jQuery

查看:70
本文介绍了在jQuery中切换div的高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题已经解决,但是没有一种解决方案对我有用.

This question has been already addressed, but none of the solutions have worked for me.

我提到了这个先前解决相同问题的问题:

我注意到其中一个响应给出了此jsfiddle链接,该链接实现了与我想要,并且工作.

I noticed that one of the responses gave this jsfiddle link, which implements the exact functionality that I want, and works.

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

但是当我将框架更改为jQuery 1.4.4以外的任何格式时,只要页面加载,div就会立即消失.这是我在自己的项目中遇到的问题.

But when I changed the framework to anything but jQuery 1.4.4, the div starts instantly disappearing as soon as the page loads. This is the problem I've been having on my own project.

关于如何使jsfiddle在jquery 2.x上运行的任何想法?我想念什么?

Any ideas on how to get that jsfiddle working on jquery 2.x? What am I missing?

推荐答案

修复很简单:

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

您只需要在高度值中添加px个单位即可.

You just need to add px units to the height value.

请参见以下示例的演示: http://jsfiddle.net/audetwebdesign/3dd3s/

See demo at: http://jsfiddle.net/audetwebdesign/3dd3s/

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.

请注意,自jQuery 1.8起,对.toggle的使用已被弃用.
参考: http://api.jquery.com/toggle-event/

Note that this use of .toggle has been deprecated since jQuery 1.8.
Reference: http://api.jquery.com/toggle-event/

其他一些解决方案涉及jQuery .height()函数,该函数返回无单位像素值.在这种情况下,计算值被强制/强制转换为像素值,因此不需要"px"单位.

Some of the other solutions involve the jQuery .height() function, which returns a unit-less pixel value. In this case, the computed value is coerced/cast to be a pixel value, so the 'px` unit is not required.

在原始示例中,未使用.height()函数,因此需要指定单位以使其正常工作.

In the original example, the .height() function was not used so the units needed to be specified to make things work.

这篇关于在jQuery中切换div的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆