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

html代碼結構:

 

代碼如下:

<a href=""><img src="images/tmp_376x470.jpg" width="300" height="300" alt=""/></a>
<a href=""><img src="images/tmp_409x265.jpg" width="300" height="300" alt=""/></a>
<a href=""><img src="images/tmp_572x367.jpg" width="300" height="300" alt=""/></a>

 

樣式:

 

代碼如下:

a{width:300px;height:300px;background:#fff;border:1px solid #666;display:inline-block} /* 這裡需要指定a標簽的高寬,背景和邊框為可選 */
腳本(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);
                }
            });
        });
    });
});

 

這樣就是實現瞭圖片的等比例放大縮小瞭。

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *