【发布时间】:2019-06-05 14:38:07
【问题描述】:
首先,与下面的示例进行交互。
该组件的工作方式必须与输入类型范围完全相同。 我遇到的问题是计算步长值,并根据当前步长和最大值的比例将拇指捕捉到轨迹中(再次,就像一个范围输入)。
欢迎使用本机范围输入来控制此行为的任何响应。我没用过,只是因为卡扣不流畅。
const thumb = document.querySelector(".stepper__step");
const trail = document.querySelector(".stepper__trail");
// Variables that controls the range snap and values
var minVal = 0;
var maxVal = 20;
var step = 2;
thumb.ondragstart = function() {
return false;
};
thumb.addEventListener("mousedown", function(event) {
event.preventDefault();
addGrabbingClassFromThumb();
let shiftX = event.clientX - thumb.getBoundingClientRect().left;
// shiftY not needed, the thumb moves only horizontally
document.addEventListener("mousemove", onMouseMove);
document.addEventListener("mouseup", onMouseUp);
function onMouseMove(event) {
let newLeft = event.clientX - shiftX - trail.getBoundingClientRect().left;
// the pointer is out of trail => lock the thumb within the bounaries
if (newLeft < 0) {
newLeft = 0;
}
let rightEdge = trail.offsetWidth - thumb.offsetWidth;
if (newLeft > rightEdge) {
newLeft = rightEdge;
}
thumb.style.left = newLeft + "px";
}
function onMouseUp() {
document.removeEventListener("mouseup", onMouseUp);
document.removeEventListener("mousemove", onMouseMove);
}
});
thumb.addEventListener("mouseup", function() {
removeGrabbingClassFromThumb();
});
function addGrabbingClassFromThumb() {
thumb.className += " stepper__step--grabbing";
}
function removeGrabbingClassFromThumb() {
thumb.className = thumb.className.replace(/stepper__step--grabbing/g, "");
}
body {
background-color: #333333;
}
.stepper-wrapper {
width: 350px;
margin: 80px auto;
position: relative;
}
.stepper__trail {
height: 2px;
background-color: rgba(255, 255, 255, 0.25);
}
.stepper__step {
height: 20px;
position: absolute;
left: 0;
width: 50px;
bottom: 0;
transition: left 0.25s ease-in-out;
cursor: -webkit-grab;
cursor: grab;
}
.stepper__step:after {
content: "";
display: block;
position: absolute;
left: 0;
bottom: 0;
right: 0;
height: 100%;
background-color: #fff;
}
.stepper__step--grabbing {
cursor: -webkit-grabbing;
cursor: grabbing;
transition: unset;
}
<div class="stepper-wrapper">
<div class="stepper__step"></div>
<div class="stepper__trail"></div>
</div>
【问题讨论】:
-
你能做一个codesandbox 来说明这个功能吗?
-
@Ohgodwhy 它在 JSFiddle 上:jsfiddle.net/269j14Ln
-
Here's a quick attempt from me。为了细化可能的范围点并确保更好地尊重边界,还需要做一些数学运算。我希望这能让你朝着正确的方向前进。
-
太棒了!解决了我的问题。我正在努力完成这项工作。请给出答案,以便我投票正确。
标签: javascript html reactjs vue.js dom-events