3 回答
TA贡献1810条经验 获得超4个赞
这个怎么样:
var elements = document.getElementsByClassName("slidecontainer");
elements.forEach(function(el){
var slider = el.getElementById("myRange");
var output = el.getElementById("demo");
output.innerHTML = slider.value;
slider.oninput = function() {
output.innerHTML = this.value;
}
})
现在,对于您添加的每个滑块,它都会起作用,这意味着您只需要添加具有相应类的 html
</head>
<body>
<h1>Custom Range Slider</h1>
<p>Drag the slider to display the current value.</p>
<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="myRange">
<p>Value: <span id="demo"></span></p>
</div>
将产生两个没有额外声明的工作滑块。
所以我正在做的是寻找每个具有滑块容器类的元素并遍历每个元素。这样对于具有该结构的每个滑块,您都会有一个滑块。无需添加额外的 javascript 来引用每个滑块
TA贡献1951条经验 获得超3个赞
将滑块和输出标签作为参数来运行
function setSlider(slider, output){
var slider = document.getElementById(slider);
var output = document.getElementById(output);
output.innerHTML = slider.value;
slider.oninput = function() {
output.innerHTML = this.value;
}
}
setSlider("myRange1", "demo1")
setSlider("myRange2", "demo2")
<body>
<h1>Custom Range Slider</h1>
<p>Drag the slider to display the current value.</p>
<div class="slidecontainer">
<input type="range" min="1" max="100" value="50" class="slider" id="myRange1">
<p>Value: <span id="demo1"></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>
</body>
TA贡献1834条经验 获得超8个赞
您可以使用类名并定位容器元素,如下所示:
const containers = document.querySelectorAll(".slidecontainer");
for(let container of containers) {
const slider = container.querySelector(".slider");
const output = container.querySelector(".value");
output.innerHTML = slider.value;
slider.oninput = function() {
output.innerHTML = this.value;
}
}
<body>
<h1>Custom Range Slider</h1>
<p>Drag the slider to display the current value.</p>
<div class="slidecontainer">
<input type="range" min="1" max="100" value="50" class="slider">
<p>Value: <span class="value"></span></p>
</div>
<div class="slidecontainer">
<input type="range" min="1" max="100" value="50" class="slider">
<p>Value: <span class="value"></span></p>
</div>
<div class="slidecontainer">
<input type="range" min="1" max="100" value="50" class="slider">
<p>Value: <span class="value"></span></p>
</div>
添加回答
举报