
本文将介绍如何使用 JavaScript 限制双滑块范围选择器,防止最大值小于最小值。我们将通过监听滑块的 input 事件,并动态调整另一个滑块的值,确保范围始终有效。
首先,让我们回顾一下基本的 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;
}核心逻辑在于 JavaScript 代码,它负责监听滑块的 input 事件并进行调整:
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();代码解释:
注意事项:
总结:
通过以上步骤,我们成功实现了一个双滑块范围选择器,并限制了最小值和最大值之间的关系,防止出现无效的范围选择。 这种方法简单有效,可以方便地应用于各种需要范围选择的场景中。
以上就是限制双滑块范围:防止最大值小于最小值的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号