【问题标题】:Changing src attribute of image element and getting size properties更改图像元素的 src 属性并获取大小属性
【发布时间】:2015-08-14 11:46:39
【问题描述】:

我在通过 javascript 对 img 元素执行更改时遇到问题:

我构建了一个框架,通过键盘的箭头键循环浏览不同的图像。为此,我将所有图像 url 加载到一个数组中,然后相应地更改 img 元素的 src 属性。

到目前为止一切正常。但是现在我想显示当前图像的 naturalHeight 和 naturalWidth 。不幸的是,当我循环浏览图像时,会显示当前图像之前的图像大小,尽管元素显示了正确的图像。

这与加载顺序和渲染有关吗?

如果有人能在这个问题上帮助我,我将非常感激。

最好的问候

最大

在 cmets 上:

我只是通过以下方式加载图像:

imageLeft.setAttribute("src", imagesOld[rowCounter]);
imageRight.setAttribute("src", imagesNew[rowCounter]);

我有一个更新尺寸信息的功能:

function updateSizeInformation() {
    var imageLeftX = $find("<%= txtXImageLeft.ClientID %>");
    var imageLeftY = $find("<%= txtYImageLeft.ClientID %>");
    var imageRightX = $find("<%= txtXImageRight.ClientID %>");
    var imageRightY = $find("<%= txtYImageRight.ClientID %>");
    var imageLeft = document.getElementById("imageLeft");
    var imageRight = document.getElementById("imageRight");

    imageLeftX.set_value(imageLeft.naturalWidth);
    imageLeftY.set_value(imageLeft.naturalHeight);
    imageRightX.set_value(imageRight.naturalWidth);
    imageRightY.set_value(imageRight.naturalHeight);
}

还有一个使图像适合父 div 的函数:

function fitImagesToContainers() {
    var divLeft = document.getElementById("imageContainerLeft");
    var divRight = document.getElementById("imageContainerRight");
    var imageLeft = document.getElementById("imageLeft");
    var imageRight = document.getElementById("imageRight");

    if (imageLeft.naturalWidth > imageLeft.naturalHeight) {
        imageLeft.setAttribute("width", divLeft.clientWidth);
        imageLeft.setAttribute("height", divLeft.clientWidth * (imageLeft.naturalHeight / imageLeft.naturalWidth));
    } else if (imageLeft.naturalWidth < imageLeft.naturalHeight) {
        imageLeft.setAttribute("height", divLeft.clientHeight);
        imageLeft.setAttribute("width", divLeft.clientHeight * (imageLeft.naturalWidth / imageLeft.naturalHeight));
    }
}

【问题讨论】:

  • 你是在img标签中添加height和width属性吗,当你更新图片src时,你也可以更新heith width属性。

标签: javascript image attributes element


【解决方案1】:

当您设置页面未加载的图像元素的“src”属性时,它通常会引发对图像文件资源的异步检索。在图像 onload 事件触发后,图像元素属性应该代表检索到的图像的属性,但在此之前是不可预测的。

如果您提供的代码同步执行,则会遇到您报告的问题。

在 Mozilla Firefox(至少)中,如果在同一脚本执行中立即检查图像属性,则图像属性可以是前一个图像的属性,因为尚未检索新/下一个图像。如果页面之前加载了相同的图像,究竟会发生什么可能是不可预测的 - 我发现它立即给出了正确的尺寸值。

我使用标准 javascript 对此进行了测试,并且不希望建议如何在 jQuery 中编写 onload 事件处理程序。我确实在javascript, image onload() doesnt fire in webkit if loading same image 上遇到了这个其他 StackOerflow 问题,这可能很有趣。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-05
    • 1970-01-01
    • 2021-11-08
    • 2012-10-09
    • 1970-01-01
    相关资源
    最近更新 更多