IE javascript图像大小调整不起作用

IE javascript image resize not working

本文关键字:调整 不起作用 javascript 图像 IE      更新时间:2023-09-26

我有一些javascript在IE中不起作用。

function resize($img) {
    var max_size_w = 200;
    var max_size_h = 200;
    var h = $img.height();
    var w = $img.width();
    if (h > max_size_h) {
        h = max_size_h;
        w = Math.ceil($img.width() / $img.height() * max_size_h);
    }
    if (w > max_size_w) {
        h = Math.ceil($img.height() / $img.width() * max_size_w);
        w = max_size_w;
    }
    $img.css({ height: h, width: w });
}
$(window).load(function() {
    // Size the images correctly
    $(".personPictureImage").each(function() {
        var $img = $(this).find("img");
        $img.load(function() { resize($(this)); });
        if($img.height())
            resize($img);
    });
});

在其他所有浏览器中,它都会调整图像大小以适合200x200的框。在IE中,我得到的大小是30px乘以=28px。在chrome中,我得到了200像素乘142像素。

我知道IE有问题,通常是一个糟糕的浏览器,但我无论如何都在努力支持它。如何修复我的代码以在IE中工作?

尝试替换

var max_size_w = 200;
var max_size_h = 200;
var h = $img.height();
var w = $img.width();
if (h > max_size_h) {
    h = max_size_h;
    w = Math.ceil($img.width() / $img.height() * max_size_h);
}
if (w > max_size_w) {
    h = Math.ceil($img.height() / $img.width() * max_size_w);
    w = max_size_w;
}

通过这个计算

var MAX=200,wi=$img.width(),he=$img.height(),
r=MAX/Math.max(wi,he),
w=Math.round(wi*r),
h=Math.round(he*r);

var MAX=200,
r=MAX/Math.max(this.width,this.height),
w=Math.round(this.width*r),
h=Math.round(this.height*r);

从这里拿走。

https://stackoverflow.com/a/17502568/2450730

ps.:r是比率&我也会使用纯javascript,因为所有浏览器都支持您所做的一切。