Image resizing with Jquery Animate

孤人 提交于 2019-11-29 07:25:15

@Aron's solution is ok, but it comes with certain limitations: you can't have an image within the document flow.

My solution actually creates an absolutely positioned clone of the image and shows it on top of the original image. It calculates the original image's absolute position using .offset().

The disadvantage of this method is that if the document flow changes (such as when resizing the client window), the absolutely positioned element stays at the old position. It depends on the layout of your page if you can use this method or not.

Click on the image in my demo to toggle the effect. 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>

CSS:

#someImage { width:32px; height:32px; }

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);
});

This should not be too hard:

// increase factor
var factor = 2;

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

How this is achieved:

  • Image is increased in size with a certain ratio. In this case it is * 2, but I can imagine you want to do something smart with an upper limit or so.
  • Image top and left offset is decreased with the current dimensions divided by the increase factor.

Quick demo here.

If I understood right, here is what you want.

I show the large image with position: absolute, then your layout isn't affected by the image being resized. If you have questions about this solution, post comments here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!