如何使图像DOM元素响应

时间:2016-11-16 10:21:02

标签: javascript jquery html css

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上的像素之外的所有内容都无效

2 个答案:

答案 0 :(得分:1)

你可以使用类似的东西

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

答案 1 :(得分:0)

嗨,它可以参考codepen附件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的宽度,则会自动调整。