用于显示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粉6800005552023-09-13 00:49:21
当然有。你会很容易地识别出你自己的代码,它被包裹在一个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>