1. 程式人生 > >jquery實現頁面圖片等比例放大縮小功能

jquery實現頁面圖片等比例放大縮小功能


$(function () {
    var imgs = $('a>img');
    imgs.each(function () {
        var img = $(this);
        var width = img.attr('width');//區域寬度
        var height = img.attr('height');//區域高度
        var showWidth = width;//最終顯示寬度
        var showHeight = height;//最終顯示高度
        var ratio = width / height;//寬高比
        img.load(function () {
            var imgWidth, imgHeight, imgratio;
            $('<img />').attr('src', img.attr('src')).load(function () {
                imgWidth = this.width;//圖片實際寬度
                imgHeight = this.height;//圖片實際高度
                imgRatio = imgWidth / imgHeight;//實際寬高比
                if (ratio > imgRatio) {
                    showWidth = height * imgRatio;//調整寬度太小
                    img.attr('width', showWidth).css('margin-left', (width - showWidth) / 2);
                } else {
                    showHeight = width / imgRatio;//調高度太小
                    img.attr('height', showHeight).css('margin-top', (height - showHeight) / 2);
                }
            });
        });
    });
});