调整窗口大小时修改图像大小(jQuery)

问题描述 投票:0回答:1

我试图在加载页面和调整浏览器大小时调整图像大小。有些图像是纵向的,有些是横向的,它们将位于也可能是纵向/横向的容器 div 中(取决于浏览器大小)。图像是否应该拉伸以填充框(100% 宽度或 100% 高度)并不重要,如果比例不匹配,则会发生剪切(通过 CSS

overflow:hidden
)。

我的方法是获取容器框的比例(即纵向或横向)并获取图像比例(纵向或横向),比较它们并相应地调整CSS宽度/高度。

注意:所有容器都将具有

mr_our-dest-img-container
类,并且都仅包含 1 个 img 元素(以及一些不同的元素)。

这是我的代码,但不起作用。它没有任何作用,我也无法弄清楚。谁能帮我解决这个问题吗?

$(document).ready(function () {
    updateImageSize();
    $(window).resize(function() {
        updateImageSize();
    });
});

function updateImageSize() {
    $(".mr_our-dest-img-container").each(function(){
        var ratio_cont = jQuery(this).width()/jQuery(this).height();
        var $img = jQuery(this).find("img");
        var ratio_img = $img.width()/$img.height();
        if (ratio_cont > ratio_img)
        {
            $img.css({"width": "100%", "height": "auto"});
        }
        else if (ratio_cont < ratio_img)
        {
            $img.css({"width": "auto", "height": "100%"});
        }
    }
};
javascript jquery image-resizing window-resize
1个回答
4
投票

正如控制台所说,这是一个语法错误。您错过了

)
函数末尾的
each

function updateImageSize() {
    $(".mr_our-dest-img-container").each(function(){
        var ratio_cont = jQuery(this).width()/jQuery(this).height();
        var $img = jQuery(this).find("img");
        var ratio_img = $img.width()/$img.height();
        if (ratio_cont > ratio_img)
        {
            $img.css({"width": "100%", "height": "auto"});
        }
        else if (ratio_cont < ratio_img)
        {
            $img.css({"width": "auto", "height": "100%"});
        }
    }); //missing )
};
© www.soinside.com 2019 - 2024. All rights reserved.