我正在努力计算范围价格滑块中两个点之间的填充颜色。
范围滑块的 html 部分内容如下:
<div class="values">
<span id="range1">0</span>
<span> ‐ </span>
<span id="range2">100</span>
</div>
<div class="container">
<div class="slider-track"></div>
<input type="range" min="0" max="80" value="50" id="slider-1" oninput="slideOne()">
<input type="range" min="0" max="80" value="70" id="slider-2" oninput="slideTwo()">
</div>
JS:
window.onload = function () {
slideOne();
slideTwo();
};
let sliderOne = document.getElementById("slider-1");
let sliderTwo = document.getElementById("slider-2");
let displayValOne = document.getElementById("range1");
let displayValTwo = document.getElementById("range2");
let minGap = 5;
let sliderTrack = document.querySelector(".slider-track");
let sliderMaxValue = document.getElementById("slider-1").max;
function slideOne() {
if (parseInt(sliderTwo.value) - parseInt(sliderOne.value) <= minGap) {
sliderOne.value = parseInt(sliderTwo.value) - minGap;
}
displayValOne.textContent = sliderOne.value;
fillColor();
}
function slideTwo() {
if (parseInt(sliderTwo.value) - parseInt(sliderOne.value) <= minGap) {
sliderTwo.value = parseInt(sliderOne.value) + minGap;
}
displayValTwo.textContent = sliderTwo.value;
fillColor();
}
function fillColor() {
percent1 = (sliderOne.value / sliderMaxValue) * 100;
percent2 = (sliderTwo.value / sliderMaxValue) * 100;
sliderTrack.style.background = `linear-gradient(to right, #dadae5 ${percent1}% , #3264fe ${percent1}% , #3264fe ${percent2}%, #dadae5 ${percent2}%)`;
}
当 html 中的输入值为“0”(min="0"
)时,点之间的填充颜色一切正常。但是,当将两个输入都设置为 时min="40"
(例如), JS 中的percent1和percent2变量需要重新计算。否则,点之间的填充颜色将不再正确。
那么:在 JS 中或者在 HTML 输入中,百分比 1和百分比 2的正确计算是什么?min="20"
min="40"
示例 1 min="0"
:小提琴 1
示例 2 min="40"
:小提琴 2