Uncaught TypeError:无法读取JavaScript上未定义的属性“ style”

时间:2019-03-02 18:53:50

标签: javascript

  

未捕获的TypeError:无法读取未定义的属性'style'

这是我尝试写的消息:

/* Opacity Value */
const opacity = 0.4;

/* Set Opacity For First Image */
imgs[0].style.opacity = opacity;

HTML:

<div class="container">
    <div class="main-img">
      <img src="images/6.jpg" id="current" />
    </div>
    <div class="imgs">
      <img src="images/6.jpg" />
      <img src="images/5.jpg" />
      <img src="images/4.jpg" />
      <img src="images/6.jpg" />
    </div>
</div>

完整的Javascript代码:

const current = document.querySelector("#current");

const imgs = document.querySelectorAll(“。imgs img”);

常量不透明度= 0.4;

imgs [0] .style.opacity = opacity;

imgs.forEach(img => img.addEventListener(“ click”,imgClick));

功能imgClick(e){   imgs.forEach(img =>(img.style.opacity = 1));

current.src = e.target.src;

current.classList.add(“淡入”);

setTimeout(()=> current.classList.remove(“ fade-in”),500);

e.target.style.opacity =不透明度; }

2 个答案:

答案 0 :(得分:0)

let imgs = document.querySelectorAll('.imgs img');
// imgs[0].style.opacity = 0.4; now you can set style to array element 
imgs.forEach((img, idx) => {
	setTimeout(() => {
  	img.style.opacity = 0.4
  }, idx * 500)
})
<div class="container">
    <div class="main-img">
      <img src="images/6.jpg" id="current" />
    </div>
    <div class="imgs">
      <img src="images/6.jpg" />
      <img src="images/5.jpg" />
      <img src="images/4.jpg" />
      <img src="images/6.jpg" />
    </div>
</div>

答案 1 :(得分:0)

基本上在下一行中,您正在做的是-调用一个空数组的第一个索引值,并为其分配样式属性。您需要在数组的第一个索引中具有值才能使该段代码起作用。

imgs[0].style.opacity = opacity;

相反,您可以做的是

const opacity = 0.4;
const imgs = document.querySelectorAll('img');
if(imgs && imgs.length > 1) {
  imgs[0].style.opacity = opacity;
}

您必须在所有html代码之后将JS代码保留在正文部分的末尾,以使此功能生效。