使用JS在IE中调整图像大小时出错

时间:2017-01-16 20:55:46

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

我使用javascript来调整图像onload的大小。以下代码在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中显示的网站空间图片。 https://i.stack.imgur.com/lq60N.png

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

id“image”对应于img标签,而“image-container”对应于img标签周围的figure元素。

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

1 个答案:

答案 0 :(得分:0)

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

例如,

而不是

document.getElementById('homework').offsetWidth;

我用过

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

而不是

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

我用过

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