【问题标题】:Weird issues with image resizing in JavaScript (problems only in Firefox)在 JavaScript 中调整图像大小的奇怪问题(仅在 Firefox 中存在问题)
【发布时间】:2012-03-24 20:29:36
【问题描述】:

代码:

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 中!这是什么鬼?

【问题讨论】:

  • 使用开发者控制台跟踪 dom 元素的样式
  • 您可以使用百分比单位来设置图像的宽度,根本不需要脚本。
  • @Teemu - 你怎么想的?这不仅仅是关于宽度,如果图像很宽,那么肯定,但有一些限制(如果宽度/高度
  • 您能否提供任何链接,以便我们轻松跟踪错误的工作内容..
  • 这是一个链接:dateks.lv/cenas/3/…。单击任何图像以打开图库。我已经稍微更改了代码,但问题仍然存在。似乎出于某种奇怪的原因,Firefox 单独“记住”了先前查看的图片的 CSS 样式并将其应用于当前图像而不考虑 JS。当我再次将鼠标悬停在当前图像的缩略图上时,CSS 得到修复。

标签: javascript css image firefox cross-browser


【解决方案1】:

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

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

【讨论】:

  • dateks.lv/js/gallery.js?v=75 - 这是执行“魔术”的确切 javascript 文件。如您所见,resizeImage 仅在调整弹出窗口大小时直接调用(此处没有图像切换),在其他情况下,它在下一张图像已经预加载后调用(switchImage() 函数)。我希望浏览器知道,如果您将当前图像的 src 属性切换到不同的、已经预加载的图像,它也会自动更改图像的宽度/高度,但似乎情况并非如此使用 Firefox。
  • 再一次,规范说宽度/高​​度是异步变化的,即使切换到的图像已经预加载。
  • 那么我应该什么时候知道图像的实际宽度/高度??
  • 当 onload 触发时,就像我说的那样。
猜你喜欢
  • 2015-11-07
  • 1970-01-01
  • 2011-05-27
  • 2012-03-16
  • 1970-01-01
  • 2011-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多