【问题标题】:Error using JS to resize images in IE在 IE 中使用 JS 调整图像大小时出错
【发布时间】:2017-05-31 18:59:59
【问题描述】:

我使用 javascript 来调整加载图像的大小。以下代码在 chrome 和 firefox 中运行良好,但在 Internet Explorer 11(或任何版本)中不起作用。

function imgWidth(){
        var width = document.getElementById('homework').offsetWidth;
        document.getElementById('image').style="width: "+(940-width)+";";
        var height = document.getElementById('image-container').offsetHeight;
        var imgheight = document.getElementById('image').offsetHeight;
        if(imgheight > height){
            document.getElementById('image').style="top: -"+((imgheight - height)/2)+";width: "+(940-width)+";";
        }
        document.getElementById('image-container').style="width: "+(940-width)+";margin-left:"+(width+40)+";";
        }

下面是调用JS函数的html段:

<figure id="image-container">
    <img id="image" onload="imgWidth()" src="http://www.nasa.gov/sites/default/files/styles/full_width_feature/public/thumbnails/image/pia21376d.jpg" title="This image of a crescent Jupiter and the iconic Great Red Spot was created by a citizen scientist (Roman Tkachenko) using data from Juno's JunoCam instrument." />
</figure>

这是在 chrome 中显示的 webspace 的图像。 https://i.stack.imgur.com/lq60N.png

请注意,它会根据左侧容器的宽度调整大小。该代码还会裁剪图像,使其在容器内垂直对齐。

id "image" 对应于一个 img 标签,而 "image-container" 对应于 img 标签周围的图形元素。

再次,我正在尝试使我的代码与 IE 兼容。
这是图像在 IE 中的加载方式:https://i.stack.imgur.com/FzwsS.png

【问题讨论】:

    标签: javascript css image internet-explorer cross-browser


    【解决方案1】:

    我最终用 jQuery 替换了现有的 javascript,它现在可以工作了。

    例如代替

    document.getElementById('homework').offsetWidth;
    

    我用过

    $("#homework").outerWidth();
    

    而不是

    document.getElementById('image').style="width: "+(940-width)+";";
    

    我用过

    $("#image").css("width",(940-width));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-22
      • 2014-06-26
      • 2011-05-27
      • 1970-01-01
      • 2011-03-18
      • 2018-08-31
      • 2011-06-28
      相关资源
      最近更新 更多