开发者问题收集

未捕获的类型错误:无法设置未定义的属性(设置‘显示’)

2022-04-09
9137

我正在为我的音乐反应应用制作一个进度条。我想让进度指示器在用户将鼠标悬停在进度条容器上时显示出来。但我遇到了这个错误:未捕获的类型错误:无法设置未定义的属性(设置“显示”)

我的 Javascript:

document.getElementsByClassName('rhap_progress-container')[0].onmouseover = function(){
  document.getElementsByClassName('rhap_progress-indicator').style.display = "block";
}
document.getElementsByClassName('rhap_progress-container')[0].onmouseout = function(){
  document.getElementsByClassName('rhap_progress-indicator').style.display = "none";
}

我的 html:

<div class="rhap_progress-container" aria-label="Audio progress control" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="24.67" tabindex="0">
  <div class="rhap_progress-bar ">
    <div class="rhap_progress-indicator" style="left: 24.67%;"></div>
    <div class="rhap_progress-filled" style="width: 24.67%;"></div>
  </div>
</div>

我的 css:

.rhap_progress-indicator {
  display: none;
  width: 18px !important;
  height: 18px !important;
  border: 3px solid #232530;
  top: -7 px !important;
  box-shadow: none !important;
  opacity: 1 !important;
  content: url('./img/outlined-progress-indicator.png');
}
2个回答

document.getElementsByClassName 返回一个数组。

因此 document.getElementsByClassName('rhap_progress-indicator') 还需要选择数组的一个索引:

document.getElementsByClassName('rhap_progress-indicator')[0]

另一种方法是使用 document.querySelector('.rhap_progress-indicator') ,如果元素存在,它将返回该元素。

John
2022-04-09

使用 getElementsByClassName 时,您需要选择节点列表的索引

这适合您:

let Container = document.getElementsByClassName('rhap_progress-container');
let Indicator = document.getElementsByClassName('rhap_progress-indicator');

Container[0].onmouseover = function(){
  Indicator[0].style.display = "block";
}
Container[0].onmouseout = function(){
  Indicator[0].style.display = "none";
}

Milad
2022-04-09