
本文档旨在提供一种使用 JavaScript 实现双滑块范围限制的方法,以防止用户在调整滑块时出现最小值超过最大值,或最大值低于最小值的情况。通过监听滑块的 input 事件,并动态调整另一个滑块的值,确保范围的有效性。本文将提供详细的代码示例和解释,帮助开发者轻松实现这一功能。
核心思路是监听两个滑块的 input 事件。当一个滑块的值发生变化时,立即检查它是否超过了另一个滑块的值。如果超过,则强制将另一个滑块的值调整到临界值,从而保证最小值始终小于等于最大值。
以下是一个简洁的实现示例,展示了如何使用 JavaScript 限制双滑块的范围:
const twoRangeSlider = (() => {
const bindComponent = (item) => {
const rangeInputs = item.querySelectorAll('.js-two-range-slider-input');
item.addEventListener("input", ({ target }) => {
const [ right, left ] = rangeInputs;
if (target == right) {
left.value = Math.min(+right.value -1, +left.value);
} else {
right.value = Math.max(+left.value +1, +right.value);
}
});
};
const init = () => {
const rootEl = document.getElementsByClassName("js-two-range-slider");
[...rootEl].forEach((item) => bindComponent(item));
};
return {
init
};
})();
twoRangeSlider.init();HTML 结构
<div class="two-range-slider js-two-range-slider">
<input type="range" value="80" min="10" max="100" step="1" class="two-range-slider__input js-two-range-slider-input">
<input type="range" value="30" min="10" max="100" step="1" class="two-range-slider__input js-two-range-slider-input">
<div class="two-range-slider__output">
<p class="minmax">Min</p><input class="two-range-slider__value js-two-range-slider-min-value" type="number" value="30" min="10" max="100" step="1">
<p class="maxmin">Max</p><input style="right: -5px;" class="two-range-slider__value js-two-range-slider-max-value" type="number" value="80" min="10" max="100" step="1">
</div>
</div>CSS 样式
.two-range-slider {
position: relative;
height: 4px;
width: 164px;
margin-bottom: 50px;
}
.two-range-slider__input {
position: absolute;
left: 40%;
top: 15px;
box-shadow: 0;
appearance: none;
width: 60%;
height: 3px;
border-radius: 50px;
background-color: #000;
outline: 0;
}
.two-range-slider__value {
padding: 0px 10px;
color: #000;
position: relative;
top: 19px;
outline: none;
width: 50px;
position: absolute;
border: 1px solid #ccc;
box-sizing: border-box;
}
.two-range-slider__input::-webkit-slider-thumb {
z-index: 2;
position: relative;
-webkit-appearance: none;
appearance: none;
height: 13px;
width: 13px;
border-radius: 50%;
background: #000;
cursor: pointer;
}
.two-range-slider__input::-moz-range-thumb {
z-index: 2;
position: relative;
appearance: none;
width: 25px;
height: 25px;
border-radius: 50%;
border: 0;
background: #FFFFFF;
cursor: pointer;
}
.two-range-slider__output {
display: inline-flex;
flex-flow: row nowrap;
justify-content: space-between;
width: 140%;
top: -15px;
margin-left: 0px;
color: #000;
position: relative;
}
.range-slider__value {
padding: 0px 10px;
color: #000;
outline: none;
width: 50px;
}代码解释:
通过以上步骤,我们可以轻松实现双滑块范围的限制,确保用户在交互过程中始终保持有效的范围选择。 这种方法简单有效,可以应用于各种需要范围选择的场景。
以上就是限制双滑块范围:防止最小值超过最大值的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号