【问题标题】:Script to animate height of DIV is changing the height of DIV suddenly动画 DIV 高度的脚本正在突然改变 DIV 的高度
【发布时间】:2012-01-17 21:06:54
【问题描述】:

我有以下使用 slideUp 和 slideDown 效果的脚本,但在为 DIV 的高度设置动画时无法正常工作:

$(function () {
    var myTimer,
        myDelay = 500;

    $('.slide, .the_menu').hover(function () { 

        //when either a `img.menu_class` or a `.the_menu` element is hovered over, clear the timeout to hide the menu and slide the menu into view if it already isn't
        clearTimeout(myTimer);

            $('.the_menu').animate({height:'37px'},'fast', function () { $('.the_menu').stop(true, true).fadeIn('slow'); });


    },
    function () {

        //when either a `img.menu_class` or a `.the_menu` element is hovered out, set a timeout to hide the menu
        myTimer = setTimeout(function () {
        $('.the_menu').stop(true, true).fadeOut('slow', function () { $('.the_menu').animate({height:'0px'},'fast');                });}, myDelay);
    });
});

您可以在this page 上看到它的实际效果。将鼠标悬停在导航栏中的第二个“主页”图像上。

问题在于 DIV 高度上的动画似乎无法正常工作,即没有平滑过渡,而是高度突然变化。

谁能告诉我为什么?

谢谢,

尼克

【问题讨论】:

    标签: jquery height jquery-animate


    【解决方案1】:

    问题是您在降低高度动画之前进行淡入淡出,在增加高度之后进行淡入淡出。所以:

    1. 在动画高度降低之前,您的 div 没有任何内容,因此其高度已更改为 cero。
    2. 在动画高度增加后你的 div 有了内容,所以它的高度已经是 37px。

    【讨论】:

    • 谢谢。我现在已经实现了下面 amelvin 建议的方法。这适用于 slideDown,但我想知道是否有一种方法可以在保持淡出的同时进行 slideUp,因为我更喜欢这种效果。
    • 浮动 div 保持其大小,即使它没有任何内容。所以你应该给你的 div 添加这个 css 属性:“floating:left;”并在其前添加一个空的 div 并使用“clear:both;”。现在它保持定义的高度,您可以对其进行动画处理。
    【解决方案2】:

    如果您在想要显示菜单时更改动画以使用 slideDown('slow') - 您将看到高度的逐渐变化。如:

        $('.the_menu').slideDown({height:'37px'},'slow', function () {   
      $('.the_menu').stop(true, true).fadeIn('slow'); });
    

    对于 slideUp,您最好先滑动然后隐藏菜单 - 而不是在删除之前淡出菜单。

    http://jsfiddle.net/amelvin/cfFTU/

    【讨论】:

    • 谢谢,这适用于 slideDown。对于slideUp,我想知道是否有一种方法可以包含淡出,因为我更喜欢这种效果而不是单独使用slideUp。
    猜你喜欢
    • 2012-05-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-06
    • 1970-01-01
    相关资源
    最近更新 更多