如何使图像DOM元素响应

How to make image DOM element responsive

本文关键字:元素 响应 DOM 图像 何使      更新时间:2023-09-26
var img = document.createElement("img");
    img.src = screenshots[i].content;
    img.height = '1000';
    img.width = '1000';
    item.appendChild(img);

我想要的高度和宽度是自动或%,但它似乎不与它一起工作。

我也试过

img.className = 'screenshot';
.screenshot {
   height = '100%';
   width = '100%';
}

除了在DOM上设置高度和宽度为像素之外,其他的都不起作用

你可以这样写

img
{
  width:100%;
  height:auto;
}

嗨,它的工作原理参考相互依赖的附件http://codepen.io/anilnamde/pen/aBmLdj

// HTML
<div id="xx">
</div>
// CSS
div{
  background:red;
  width:400px;
}
img{
  width:100%;
  height:auto;
}
// Javascript
var img = document.createElement("img");
img.src ='https://www.google.co.in/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png';
document.getElementById('xx').appendChild(img);

如果你改变了CSS中div的宽度,图像会自动调整。