使用Jquery Animate调整图像大小

Pet*_*ket 5 jquery image jquery-animate

是否有可能从中心向外而不是从左到右(从上到下)制作动画?我试图实现的效果类似于灯箱,当您单击图像并向外扩展时.

谢谢!

Aro*_*eel 10

这不应该太难:

// increase factor
var factor = 2;

$('#foo').click(function() {
    $(this).animate({
        top: '-=' + $(this).height() / factor,
        left: '-=' + $(this).width() / factor,
        width: $(this).width() * factor
    });
});
Run Code Online (Sandbox Code Playgroud)

如何实现:

  • 图像的大小以一定的比例增加.在这种情况下,它是* 2,但我可以想象你想做一个聪明的事情上限左右.
  • 图像顶部和左侧偏移量随着当前尺寸除以增加系数而减小.

这里快速演示.


Dar*_*JDG 2

@Aron 的解决方案是好的,但它有一定的限制:文档流中不能有图像。

我的解决方案实际上创建了图像的绝对定位克隆并将其显示在原始图像之上。它使用 计算原始图像的绝对位置.offset()

这种方法的缺点是,如果文档流发生变化(例如调整客户端窗口大小时),绝对定位的元素将保持在旧位置。是否可以使用此方法取决于您的页面布局。

单击我的演示中的图像以切换效果。http://jsfiddle.net/Xhchp/3/

HTML:

<p>Some random text.</p>
<p>More blah. <img id="someImage" src="http://upload.wikimedia.org/wikipedia/commons/thumb/1/16/Deletion_icon.svg/600px-Deletion_icon.svg.png"/> More blah.</p>
<p>Some random text.</p>
Run Code Online (Sandbox Code Playgroud)

CSS:

#someImage { width:32px; height:32px; }
Run Code Online (Sandbox Code Playgroud)

javascript:

function ZoomIn(){
    var p = $(this).offset();
    var w = $(this).width();
    var h = $(this).height();
    var $clone = $(this).clone();
    $clone.css({
        position: "absolute",
        left: p.left + "px",
        top: p.top + "px",
        "z-index": 2
    }).appendTo('body');
    $clone.data("origWidth",w);
    $clone.data("origHeight",h);
    $clone.data("origTop",p.top);
    $clone.data("origLeft",p.left);
    $clone.animate({
        top: "-=" + Math.floor(h * 0.5),
        left: "-=" + Math.floor(w * 0.5),
        width: Math.floor(w * 2),
        height: Math.floor(h * 2)
    },function(){
    });
    $clone.click(ZoomOut);
}

function ZoomOut(){
    var w = $(this).data("origWidth");
    var h = $(this).data("origHeight");
    var t = $(this).data("origTop");
    var l = $(this).data("origLeft");
    $(this).animate({
        top: t,
        left: l,
        width: w,
        height: h
    },function(){
        $(this).remove();
    });
}

$(function(){
    $('img').click(ZoomIn);
});
Run Code Online (Sandbox Code Playgroud)