【问题标题】:The image's dimension is different from when it's loading and after it loads图像的尺寸与加载时和加载后不同
【发布时间】:2011-04-17 08:00:21
【问题描述】:

我有一个页面加载了很多相当大的图像(大约 200 个 100Kb 图像 [大约 600 x 400 像素])。

如果照片是纵向的,而不是横向的,我要做的是操纵照片。

我遇到的问题是,当我在加载时使用 javascript 抓取肖像照片的属性时,高度明显低于应有的高度,而宽度则超过了应有的高度。具体来说,75 x 100 的图像被视为 100 x 16。因此,当函数运行此图像时,图像被视为横向,而不是纵向,并跳过。

我很难确定问题所在,因为该属性在加载完成后将其显示为 75 x 100 像素的图像。

有没有办法解决这个问题?还是在加载完所有图像后运行该函数?

【问题讨论】:

    标签: javascript html ajax image-processing


    【解决方案1】:

    加载后运行函数,你可以这样做:

    仅使用 DOM

    var newImg = document.createElement('img');
    newImg.src = "theImage.png";
    newImg.alt = "Always specify an alternate text for accessibility, even if left blank";
    newImg.onload = function () {
        //Image manipulation
    };
    galleryNode.appendChild(newImg); //Replace galleryNode with the parent element of your image.
    

    使用innerHTML

    galleryNode.innerHTML += "<img src='theImage.png' alt='' id='newImage1'/>";
    var newImg = document.getElementById('newImage1');
    newImg.onload = function () {
        //Image manipulation
    };
    

    使用 jQuery

    $('.gallery img').live('load',function () {
        //Image manipulation
    });
    

    【讨论】:

      【解决方案2】:

      在页面元素完成加载后运行 javascript 总是一个好主意。我通常在 jQuery 中执行此操作,如下所示:

      $(function(){
        //code to run after load goes here
      });
      

      否则,您可以尝试修改body标签并为其赋予onload属性,例如:

      <body onload="myFunction();" >
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-11
        • 2013-02-11
        • 2016-12-18
        • 1970-01-01
        • 2016-06-01
        • 2021-11-25
        相关资源
        最近更新 更多