简单的背景图像未从 for of 循环应用于父级

我试图找出这里可能的基本错误。我只是想让背景图像应用于父.img-wrap类而不是图像本身。


添加背景颜色有效,但背景图像失败。任何想法为什么?


var imgs = document.querySelectorAll('.img-wrap img');


for (let img of imgs) {

  let imgSrc = img.getAttribute("src");

  img.parentNode.style["background-image"] = imgSrc;

  /* this works: img.parentNode.style["background-color"] = 'blue'; */

}

img {

  width: 100px;

  object-position: -9999px; /* hides image */

  border: 1px solid red;

}

.img-wrap {

  float: left;

}

<div class='img-wrap'>

  <img src = 'https://i.ytimg.com/vi/dw5eILfy-c8/maxresdefault.jpg'>

</div>

<div class='img-wrap'>

  <img src = 'https://i.ytimg.com/vi/dw5eILfy-c8/maxresdefault.jpg'>

</div>

<div class='img-wrap'>

  <img src = 'https://i.ytimg.com/vi/dw5eILfy-c8/maxresdefault.jpg'>

</div>

代码笔:https ://codepen.io/anon/pen/MNydoe


感谢这里的任何帮助。


森林海
浏览 130回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript