javascript - 在 JavaScript 中调整图像大小的奇怪问题(仅在 Firefox 中有问题)

标签 javascript css image firefox cross-browser

代码:

function resizeImage()
{
    // this just dynamically changes the width of the wrapper depending on the popup width
    // to properly calculate what size should the image be fit into
    var largeWidth = gallery.offsetWidth - 300;
    setStyle(div, "width: " + largeWidth + "px");
    maxWidth = div.offsetWidth;
    if (maxWidth < 300) // can only happen if CSS max-width is not supported
    {
        maxWidth = 300;
    }
    maxHeight = div.offsetHeight - 60;
    if (maxHeight < 240)
    {
        maxHeight = 240;
    }
    var style = "width: " + ((origWidth > maxWidth) ? maxWidth : origWidth) + "px;";
    setStyle(img, style); // at this point the image is fit into the wrapper by width, still need to check the height
    if (img.height >= maxHeight) // the height is out of bounds
    {
        style = "height: " + maxHeight + "px;";
    }
    else // height is not enough, pad it by half (hack for vertical-align: middle...)
    {
        style += 'padding-top: ' + Math.floor((maxHeight - img.height) / 2) + "px";
    }
    setStyle(img, style);
}

问题:
我测试的每个浏览器(IE 7、8、9 文档模式(填充和边距:自动在 Quirks 模式下不起作用,所以没有居中)、Safari 5.1.2、Opera 11.61、Chrome 17.0.963.66)在这项工作中做得相当好,无论我切换图像的速度有多快,填充总是正确的(大图像右侧有缩略图,也可以使用箭头键切换图像)。但是 Firefox 10.0(.2) 有一个奇怪的问题:当您切换图像时,填充/高度经常被破坏(有时填充比应有的多 3 倍或根本不存在,或者高度不存在) '开关等)。 Firefox 调整图像大小的方式有问题吗?因为我不明白为什么只有 Firefox 这样做(即使是该死的 IE 与 FF 相比也能完美运行)。

如果需要更多信息,请询问。当然,我可以只添加指向实际页面的链接,但我不确定是否允许这样做,所以我暂时不会这样做。

编辑:好的,我已经设法更接近问题了(我认为)。当我更改图像源 (img.src) 和 console.log img.width 和 img.height 时,源更改但宽度和高度不会!而且它只发生在 Firefox 中!那是什么鬼?

最佳答案

当您更改 .src 时,规范会说新图像是异步加载的。即使它已被“预加载”也是如此。这意味着取决于当前加载的图像的宽度/高度也会异步更改。

因此,如果您设置 .src 并立即读取宽度/高度,您应该根据规范获得旧图像尺寸。使用 onload 处理程序等待图像实际加载?

关于javascript - 在 JavaScript 中调整图像大小的奇怪问题(仅在 Firefox 中有问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9599327/

相关文章:

javascript - 使用 javascript Controller 中的复选框

javascript - 动态宽度测量 : ReactJS/NodeJS & HTML/CSS

java - 将上传的文件保存在服务器上

cocoa - 在 NSTableView 中显示图像

java - 如何在 Java 中锁定和解锁 URL

javascript - $.extend() 不合并选项

css - 有什么方法可以忽略副本上的 css 样式吗?

css - 动态居中更新进度 Gif

jquery - 通过 CSS 或 jQuery 将导航栏变成全宽搜索栏

android - 如何将图像从设备上传到服务器以及如何在进度条上显示已上传多少数据?