调整图像大小'使用jQuery Animation的原始维度

Resize Image to it's original dimension using jQuery Animation

本文关键字:Animation jQuery 原始 使用 图像 调整      更新时间:2023-09-26

我想使用jQuery将图像从200 x 300px设置为原始大小。

我有这张照片:

var imgHtml = "<img id='bigImg' src='" + bigSrc + "' alt='' style='"height:200px; width:300px'"/>";
$("#divId").html(imgHtml);

这个jQuery代码:

$("#bigImg").animate({
    height: "400px",
    width: "600px",
},500);

它工作得很好,但实际上我必须对未来的尺寸进行硬编码。我想将动画设置为原始大小。

我该怎么做?

尝试执行此

HTML

<div id="divId">Loading</div>
<input id="submit" type="button" value=" Click Me " />

JavaScript

var bigSrc = "Image Source";
var img = new Image(),
    oWidth, oHeight;
img.onload = function() {
    oWidth = this.width;
    oHeight = this.height;
    this.width = 300;
    this.height = 200;
    this.id = "bigImg";
}
img.src = bigSrc;
$("#submit").click(function(e) {
    $("#divId").append(img);
    $("#bigImg").animate({
        height: oHeight,
        width: oWidth,
    }, 500);
});​

查看此演示jsFiddle

你可以根据自己的喜好进行调整。希望这对你有帮助。

好吧,我明白你现在的意思了。

$("#bigImg").width()将返回以px为单位的宽度,而height将执行类似操作。也可以使用.outerWidth().innerWidth()分别包含填充/边界或仅包含填充。

从您的代码中,您已经通过使用内联样式更改了图像的原始尺寸。相反,保存图像尺寸,在jQuery中将图像更改为200 x 300px,执行您想要的操作,然后将其更改回原始尺寸:

var originalWidth = $("#bigImg").width();
var originalHeight = $("#bigImg").height();
$("#bigImg").css({
    width: '200px',
    height: '300px'
});
//Do whatever you meant to do here, the when you're finished...
$("#bigImg").animate({
    width: originalWidth,
    height: originalHeight,
},500);

jQuery文档:http://api.jquery.com/animate/或http://api.jquery.com/category/dimensions/