gpt4 book ai didi

javascript - 如何在用户释放范围 slider 时触发 "change"事件,即使值未更改

转载 作者:行者123 更新时间:2023-11-30 11:08:44 39 4
gpt4 key购买 nike

var control = $('#control');

var zone = 2;
const SNAP_TARGET = 1;
const SNAP_DISTANCE = 0.1;
const LEEWAY = 0.01;

function getSliderInfo() {
const sliderVal = parseFloat(control.val());
return [sliderVal, sliderVal - SNAP_TARGET];
}

control.on('input', function () {
const [position, difference] = getSliderInfo();
let offset = -difference;
if (difference < 0 && zone === 3) {
if (difference <= -SNAP_DISTANCE) {
zone = 1;
}
}
else if (difference > 0 && zone === 1) {
if (difference >= SNAP_DISTANCE) {
zone = 3;
}
}
else {
offset = 0;
if (zone === 2) {
if (Math.abs(difference) > LEEWAY) {
zone = difference < 0 ? 1 : 3;
}
else {
control.val(1);
}
}
}
control.val(position + offset);
});

control.on('change', function () {
const difference = getSliderInfo()[1];
if (Math.abs(difference) <= LEEWAY) {
control.val(1);
zone = 2;
}
console.log('change event occured');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id='control' type='range' min='0' max='2' value='1' step='any'>

我制作了一个具有额外功能的 slider ,允许用户轻松地将其设置到准确的中心。尝试一下,看看它如何在中间停止,但如果继续将其拖过停止区域或以其他方式拖动,则可以将其滑动到任何位置。

如果用户将 slider 旋钮拖动到中点并松开鼠标,“粘性”应该被移除,这样当他们再次开始拖动时它就不会“卡住”。

问题是,如果用户将其从开始的中点滑开,然后又将其滑回中点,change 事件将不会触发,因为最终值实际上并没有改变。

我尝试使用 mouseup/pointerup 而不是 change 但有时它不起作用。您可以单击并按住 slider 旋钮,然后将光标垂直移动到 slider 区域之外,然后松开鼠标。 mouseup/pointerup 事件不会触发,因为您在光标超出输入范围时释放了按钮。

如何在用户释放范围 slider 时触发 change 事件,即使值没有改变?

最佳答案

通过点击替换更改:-

var control = $('#control');

var zone = 2;
const SNAP_TARGET = 1;
const SNAP_DISTANCE = 0.1;
const LEEWAY = 0.01;

function getSliderInfo() {
const sliderVal = parseFloat(control.val());
return [sliderVal, sliderVal - SNAP_TARGET];
}

control.on('input', function () {
const [position, difference] = getSliderInfo();
let offset = -difference;
if (difference < 0 && zone === 3) {
if (difference <= -SNAP_DISTANCE) {
zone = 1;
}
}
else if (difference > 0 && zone === 1) {
if (difference >= SNAP_DISTANCE) {
zone = 3;
}
}
else {
offset = 0;
if (zone === 2) {
if (Math.abs(difference) > LEEWAY) {
zone = difference < 0 ? 1 : 3;
}
else {
control.val(1);
}
}
}
control.val(position + offset);
});

control.on('mouseup', function () {
const difference = getSliderInfo()[1];
if (Math.abs(difference) <= LEEWAY) {
control.val(1);
zone = 2;
}
console.log('change event occured');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id='control' type='range' min='0' max='2' value='1' step='any'>

关于javascript - 如何在用户释放范围 slider 时触发 "change"事件,即使值未更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54642826/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com