我有一个滑块,当它触发鼠标移动事件时,我想在一个段落内显示其值。

这是我正在使用的代码:

var exit = document.getElementsByTagName("p");
var slide = document.getElementById('slider');
window.addEventListener("load", function(){
    slide.addEventListener("mousemove", function() {
    console.log(slide.value);
});


HTML

<input type="range" value="0" min="0" max="10" id="slider">
<p></p>


我的问题是我收到“无法读取null的属性'addEventListener'”错误。有任何想法吗?

最佳答案

我认为您想为input事件而不是mousemove事件添加事件监听器。

input事件在范围输入更改值而不是鼠标恰好在范围选择器上移动时触发。

正如@Gersey指出的那样,当用户使用箭头键更改值时,将触发input事件。

这是一个突出问题的演示



window.onload = function() {
  var slide = document.getElementById('slider'),
    p1 = document.querySelector('#oninput'),
    p2 = document.querySelector('#onmousemove');

  slide.addEventListener("input", function() {
    p1.textContent += ' ' + slide.value;
  });

  slide.addEventListener("mousemove", function() {
    p2.textContent += ' ' + slide.value;
  });
};

div.display {
  display: inline-block;
  width: 40%;
  height: 200px;
  border: 1px solid black;
}
div {
  overflow: hidden;
}

<input type="range" value="0" min="0" max="10" id="slider" />

<div>
  <div class="display" id="oninput"></div>
  <div class="display" id="onmousemove"></div>
</div>

关于javascript - 无法读取滑块上的null属性'addEventListener',我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29049077/

10-12 00:26
查看更多