JavaScript为多个滑块输出html范围滑块值

时间:2019-06-12 12:21:58

标签: javascript html

我想在html中创建两个范围滑块,并在每个滑块下方使用JS脚本显示其当前值。但是在我的代码中,两个滑块都将它们的值输出到相同的“值输出”(一个带有id="myRange2"的滑块)。为什么会发生这种情况,我该如何解决?

enter image description here

我试图使每个滑块脚本的slideroutput变量唯一,但这不能解决我的问题。

This的问题类似,但是我对JS不太熟悉,我认为我的解决方案可能更简单。

这是我的.html代码,结尾是JS脚本:

<!DOCTYPE html>
<html>
<head>

</head>
<body>

<div class="slidecontainer">
  <input type="range" min="1" max="100" value="50" class="slider" id="myRange">
  <p>Value: <span id="demo"></span></p>
</div>

<div class="slidecontainer">
  <input type="range" min="1" max="100" value="50" class="slider" id="myRange2">
  <p>Value: <span id="demo2"></span></p>
</div>

<script>
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
output.innerHTML = slider.value;

slider.oninput = function() {
  output.innerHTML = this.value;
}
</script>

<script>
var slider = document.getElementById("myRange2");
var output = document.getElementById("demo2");
output.innerHTML = slider.value;

slider.oninput = function() {
  output.innerHTML = this.value;
}
</script>

</body>
</html>

1 个答案:

答案 0 :(得分:1)

您必须对变量使用不同的名称

<!DOCTYPE html>
<html>
<head>

</head>
<body>

<div class="slidecontainer">
  <input type="range" min="1" max="100" value="50" class="slider" id="myRange">
  <p>Value: <span id="demo"></span></p>
</div>

<div class="slidecontainer">
  <input type="range" min="1" max="100" value="50" class="slider" id="myRange2">
  <p>Value: <span id="demo2"></span></p>
</div>

<script>
var slider1 = document.getElementById("myRange");
var demo = document.getElementById("demo");
demo.innerHTML = slider1.value;

slider1.oninput = function() {
  demo.innerHTML = this.value;
}
</script>

<script>
var slider2 = document.getElementById("myRange2");
var output = document.getElementById("demo2");
output.innerHTML = slider2.value;

slider2.oninput = function() {
  output.innerHTML = this.value;
}
</script>

</body>
</html>