范围与数字输入绑定的滑块可以通过以下几种方式实现:
示例代码:
<input type="range" id="slider" min="0" max="100" value="50">
<input type="number" id="input">
<script>
var slider = document.getElementById("slider");
var input = document.getElementById("input");
slider.addEventListener("input", function() {
input.value = slider.value;
});
input.addEventListener("input", function() {
slider.value = input.value;
});
</script>
示例代码(使用jQuery UI):
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<input type="range" id="slider" min="0" max="100" value="50">
<input type="number" id="input">
<script>
$(function() {
$("#slider").slider({
slide: function(event, ui) {
$("#input").val(ui.value);
}
});
$("#input").on("input", function() {
var value = $(this).val();
$("#slider").slider("value", value);
});
});
</script>
示例代码:
<div id="slider" class="slider">
<div id="handle" class="handle"></div>
</div>
<input type="number" id="input">
<style>
.slider {
width: 200px;
height: 10px;
background-color: #ccc;
position: relative;
cursor: pointer;
}
.handle {
width: 20px;
height: 20px;
background-color: #666;
position: absolute;
top: -5px;
left: 0;
cursor: grab;
}
</style>
<script>
var slider = document.getElementById("slider");
var handle = document.getElementById("handle");
var input = document.getElementById("input");
var dragging = false;
handle.addEventListener("mousedown", function() {
dragging = true;
});
document.addEventListener("mousemove", function(event) {
if (dragging) {
var sliderRect = slider.getBoundingClientRect();
var handleRect = handle.getBoundingClientRect();
var offsetX = event.clientX - sliderRect.left;
var position = offsetX / sliderRect.width;
var value = Math.round(position * 100);
if (value < 0) {
value = 0;
} else if (value > 100) {
value = 100;
}
handle.style.left = position * 100 + "%";
input.value = value;
}
});
document.addEventListener("mouseup", function() {
dragging = false;
});
input.addEventListener("input", function() {
var value = parseInt(input.value);
if (isNaN(value)) {
value = 0;
} else if (value < 0) {
value = 0;
} else if (value > 100) {
value = 100;
}
handle.style.left = value + "%";
input.value = value;
});
</script>
以上是实现范围与数字输入绑定的滑块的几种常见方式,具体选择哪种方式取决于项目需求和开发者的偏好。腾讯云提供了丰富的云计算产品和服务,可以根据具体需求选择适合的产品。
领取专属 10元无门槛券
手把手带您无忧上云