在页面加载时将图像从大到小调整大小

时间:2014-04-11 21:49:10

标签: javascript jquery css3

我想要在200px200px暂时加载一张图片,然后在页面加载时平滑缩放到50px。我用显示/隐藏技术完成了它,显示更大的>然后隐藏>显示较小的淡出;但我需要过渡。

到目前为止。但结果很难看 -

var bigSrc = "averycoolimage.jpg";

var img = new Image(),
    oWidth, oHeight;

img.onload = function() {
    oWidth = this.width;
    oHeight = this.height;
    this.width = 100;
    this.height = 50;
    this.id = "bigImg";
}
img.src = bigSrc;

$(function() {
    $("#divId").append(img);

    $("#bigImg").animate({
        height: oHeight,
        width: oWidth,
    }, 500);
});

2 个答案:

答案 0 :(得分:3)

使用CSS3过渡而不是CSS3或JS动画来解决问题略有不同。

<强> HTML

<img src="http://img1.wikia.nocookie.net/__cb20120923041524/kongregate/images/0/03/Awesome_face.png" />

<强> CSS

img {
    -webkit-transition:all .5s;
    transition:all .5s;
    width:200px;
    height:200px;
}
img.small {
    height:50px;
    width:100px;
}

<强>的Javascript

$( document ).ready(function() {
    $('img').addClass('small');
});

Fiddle Example

答案 1 :(得分:2)

您也可以使用CSS3动画(因此不使用JavaScript):

img {
     width: 50px;
    -moz-animation: scale 0.5s; /* Firefox */
    -webkit-animation: scale 0.5s; /* Safari and Chrome */
    -o-animation: scale 0.5s; /* Opera */
    animation: scale 0.5s;
}
@keyframes scale {
    from {
        width:200px;
    }
    to {
        width:50px;
    }
}
@-moz-keyframes scale { /* Firefox */
    from {
        width:200px;
    }
    to {
        width:50px;
    }
}
@-webkit-keyframes scale { /* Safari and Chrome */
    from {
        width:200px;
    }
    to {
        width:50px;
    }
}
@-o-keyframes scale { /* Opera */
    from {
        width:200px;
    }
    to {
        width:50px;
    }
}

JSFiddle:http://jsfiddle.net/a4Cm7/1/