gpt4 book ai didi

jQuery 动画 - 平滑大小过渡

转载 作者:行者123 更新时间:2023-12-03 21:30:16 24 4
gpt4 key购买 nike

所以这可能非常简单,但我还没有找到任何可以学习的例子,所以请耐心等待。 ;)

这基本上就是我想做的事情:

<div>Lots of content! Lots of content! Lots of content! ...</div>

....

$("div").html("Itsy-bitsy bit of content!");

当注入(inject)新内容时,我希望在内容较多的 div 尺寸与内容很少的 div 尺寸之间平滑地进行动画处理。

想法?

最佳答案

试试这个 jQuery 插件:

// Animates the dimensional changes resulting from altering element contents
// Usage examples:
// $("#myElement").showHtml("new HTML contents");
// $("div").showHtml("new HTML contents", 400);
// $(".className").showHtml("new HTML contents", 400,
// function() {/* on completion */});
(function($)
{
$.fn.showHtml = function(html, speed, callback)
{
return this.each(function()
{
// The element to be modified
var el = $(this);

// Preserve the original values of width and height - they'll need
// to be modified during the animation, but can be restored once
// the animation has completed.
var finish = {width: this.style.width, height: this.style.height};

// The original width and height represented as pixel values.
// These will only be the same as `finish` if this element had its
// dimensions specified explicitly and in pixels. Of course, if that
// was done then this entire routine is pointless, as the dimensions
// won't change when the content is changed.
var cur = {width: el.width()+'px', height: el.height()+'px'};

// Modify the element's contents. Element will resize.
el.html(html);

// Capture the final dimensions of the element
// (with initial style settings still in effect)
var next = {width: el.width()+'px', height: el.height()+'px'};

el .css(cur) // restore initial dimensions
.animate(next, speed, function() // animate to final dimensions
{
el.css(finish); // restore initial style settings
if ( $.isFunction(callback) ) callback();
});
});
};


})(jQuery);

评论者 RonLugge 指出,如果您在同一个元素上调用它两次,并且第一个动画在第二个动画开始之前尚未完成,这可能会导致问题。这是因为第二个动画将把当前(动画中间)大小作为所需的“结束”值,并继续将它们修复为最终值(有效地停止动画的轨道,而不是朝着“自然”大小进行动画处理) )...

解决此问题的最简单方法是调用 stop()在调用 showHtml() 并为第二个 (jumpToEnd) 参数传递 true 之前:

$(selector).showHtml("new HTML contents")
.stop(true, true)
.showHtml("even newer contents");

这将导致第一个动画在开始新动画之前立即完成(如果它仍在运行)。

关于jQuery 动画 - 平滑大小过渡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/244758/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com