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

标签 javascript css image internet-explorer cross-browser

我使用 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 中显示的网络空间图像。 /image/lq60N.png

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

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

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

最佳答案

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

例如代替

document.getElementById('homework').offsetWidth;

我用过

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

而不是

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

我用过

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

关于javascript - 在 IE 中使用 JS 调整图像大小时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41684861/

相关文章:

javascript - 如何让复选框删除表单中的 'required' 验证

javascript - Cordova 移动应用程序的 jQuery 值未更新结果

html - 背景图像未显示在页面上

javascript - 在我的网站中包含网站的一部分

Java:沿圆形路径移动标签

php - Laravel 5.1 多个图像 move() 问题

JavaScript 正则表达式查找 PHP 标签

javascript - 取消 getUserMedia 请求

javascript - 悬停时使用淡入淡出效果交换图像

javascript - 如何使用javascript将图像转换为字节数组,仅将图像存储在sql服务器上?