取消img的css属性宽度和高度(不能使用“auto”)

nullify css property width and height for img (can't use "auto")

本文关键字:不能 auto 高度 css img 属性 取消      更新时间:2023-09-26

我为网站构建了一个插件(例如WP),我需要在插件中取消img元素的css属性宽度和高度,以避免网站css(主题css)的影响。

我不能使用"auto",因为行为有点不同。在这种情况下,浏览器会忽略html属性width和height,但我需要在图像仍在加载时以正确的大小渲染元素。

如果我根据html属性的值通过javascript显式设置css属性的宽度和高度,那么一些浏览器(FF&IE)在加载过程中会忽略这一点(不知道为什么)。

在这种情况下,以下代码片段:

var img = document.getElementsByTagName('img')[0];
img.style.width = '100px';
img.style.height = '100px';
console.log(img.style.width);
console.log(img.offsetWidth);

在FF和IE中输出以下内容:

100px
0

有什么想法吗?

谢谢,Helmut

好吧,你可以为这个图像制作一个宽度和高度为100px的父div,然后将图像的宽度和高度设置为100%
这应该行得通。