使用JS显示HTML范围滑块的值
P粉988025835
P粉988025835 2023-09-13 00:42:58
0
1
596

用于显示HTML范围滑块值的JS对于第一个项目(A1)运行良好。然而,我也想将其用于A2项目(实际上有20个项目,所以需要重复使用19次)。是否有一种方法可以为多个迭代编写代码?

 const slideValue = document.querySelector("span");
      const inputSlider = document.querySelector("input");
      inputSlider.oninput = (()=>{
        let value = inputSlider.value;
        slideValue.textContent = value;
        slideValue.style.left = (value/.1) + "%";
        slideValue.classList.add("show");
      });
      inputSlider.onblur = (()=>{
        slideValue.classList.remove("show");
      });
<body>
<div class="itemstatement">A1. Blah Blah Blah.</div>
<div class="range">
<div class="sliderValue"><span>0</span></div>
<div class="field">
<div class="value left">0</div>
<input type="range" id="A1" name="A1" min="0" max="10" value="0" steps="1">
<div class="value right">10</div>
</div></div>

<div class="itemstatement">A2. Blah Blah Blah.</div>
<div class="range">
<div class="sliderValue"><span>0</span></div>
<div class="field">
<div class="value left">0</div>
<input type="range" id="A2" name="A2" min="0" max="10" value="0" steps="1">
<div class="value right">10</div>
</div></div></div></body>

P粉988025835
P粉988025835

全部回复(1)
P粉680000555

当然有。你会很容易地识别出你自己的代码,它被包裹在一个for循环内。

var elems = document.querySelectorAll(".range");
elems.forEach(function(elem) {
  const slideValue = elem.querySelector("span");
  const inputSlider = elem.querySelector("input");
  inputSlider.oninput = (() => {
    let value = inputSlider.value;
    slideValue.textContent = value;
    slideValue.style.left = (value / .1) + "%";
    slideValue.classList.add("show");
  });
  inputSlider.onblur = (() => {
    slideValue.classList.remove("show");
  });
})
<div class="itemstatement">A1. Blah Blah Blah.</div>
<div class="range">
  <div class="sliderValue"><span>0</span></div>
  <div class="field">
    <div class="value left">0</div>
    <input type="range" id="A1" name="A1" min="0" max="10" value="0" steps="1">
    <div class="value right">10</div>
  </div>
</div>

<div class="itemstatement">A2. Blah Blah Blah.</div>
<div class="range">
  <div class="sliderValue"><span>0</span></div>
  <div class="field">
    <div class="value left">0</div>
    <input type="range" id="A2" name="A2" min="0" max="10" value="0" steps="1">
    <div class="value right">10</div>
  </div>
</div>
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板