javascript - 我如何获得每个滑块的价值;javascript只显示一个
问题描述
我很难做到这一点,如果有人知道一个非常感谢的解决方案,我希望得到一些帮助。!仍在学习 java-script 并最终学习加载功能,但现在我在尝试显示两个值时遇到了问题。如果我改变任何东西,我会让第二个滑块工作,但第一个滑块停止工作。
HTML 代码:
<input type="range" min="1" max="100" value="1" class="slider" id="myRange">
<p id="value-box">Value: <span id="demo" style="color:#ae81ff;"></span><name id="Seconds"> Seconds</id></p>
<input type="range" min="1" max="200" value="1" class="slider" id="W-range">
<p id="value-box">Value: <span Name="W-range" id="demo2" style="color:#ae81ff;"></span><name id="Seconds"> Seconds</id></p>
Javascript代码:
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
output.innerHTML = slider.value;
slider.oninput = function() {
output.innerHTML = this.value;
}
}
window.onload = ()=>{
var slider = document.getElementById("W-range");
var output = document.getElementById("demo2");
output.innerHTML = slider.value;
slider.oninput = function() {
output.innerHTML = this.value;
}
}
解决方案
首先将slider
变量设置为myRange
滑块,然后重新定义slider
并将其指向W-range
滑块。您应该有两个单独的变量。window.onload
此外,如果您只是将您的放在结束标签script
之前,则根本不需要。body
此外,没有name
HTML 元素,然后您获得了带有结束id
标签的元素,该标签也不存在。这些应该只是span
元素。而且,你不能有两个相同的元素id
,你正在用id="Seconds"
. 实际上,您应该首先避免使用id
's,因为它们会使您的代码更脆弱且更难扩展。这些元素在这里根本不需要唯一的名称。
此外,由于两个滑块的作用相同,因此您只需编写一次回调代码。请参阅下面的内联评论:
<input type="range" min="1" max="100" value="1" class="slider" id="myRange">
<p id="value-box">Value:
<span style="color:#ae81ff;"></span>
<span> Seconds</span>
</p>
<input type="range" min="1" max="200" value="1" class="slider" id="W-range">
<p id="value-box">Value:
<span style="color:#ae81ff;"></span>
<span> Seconds</span>
</p>
<script>
// If you place a `script` element just before the closing body tag
// there is no need for window.onload because by the time the parser
// reaches this point, all the HTML will have been loaded into memory
// Don't use event properties, use addEventListener()
document.getElementById("myRange").addEventListener("input", report);
document.getElementById("W-range").addEventListener("input", report);
// Both sliders essentially need to do the same thing, but their values
// need to go in different places. `this` will represent the slider
// that got the input and then we can get the paragraph sibling that
// comes after it and query its contents for the span that should display
// the value.
function report(event){
this.nextElementSibling.querySelector("span").textContent = this.value;
}
</script>
推荐阅读
- sql-server-2008 - 当 SQL Server 中的列数据类型为数字时,为空或空值时获取 0,否则为 max(id)
- apache-nifi - 将avro转换为json时出现NiFi异常
- php - 如何在 laravel 中配置 html 模板
- firebase - Firebase 托管多站点、1 个域、2 个子域
- docker - crontab 中的自定义 shell 脚本
- powershell - OctoPosh 函数适用于文字,但不适用于参数 (string+num)
- ios - Swift:创建用于对数组项进行分组的算法
- c# - 阻止 AspNetCore 正确启动/停止的 BackgroundService 实现
- php - 使用 laravel 查询生成器准备报告
- javascript - 对这段代码中异步如何发生感到困惑