2017-01-16 24 views
0

我使用javascript来调整图像的大小。下面的代码在Chrome和Firefox中很好用,但在Internet Explorer 11(或任何版本)中不起作用。使用JS在IE中调整图像大小的错误

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)+";"; 
     } 

下面是HTML代码段调用JS功能:

<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> 

这里是web页面的图像,因为它出现在Chrome中。 https://i.stack.imgur.com/lq60N.png

注意,它调整了左侧容器的宽度。该代码还裁剪图像,以便在其容器内垂直对齐。

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

再次,我试图让我的代码与IE兼容。
这里是如何在IE中加载图片:https://i.stack.imgur.com/FzwsS.png

回答

0

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

例如不是

document.getElementById('homework').offsetWidth; 

我用

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

代替

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

我用

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