用户释放范围滑块时,即使值未更改,如何触发“更改”事件

时间:2019-02-12 04:28:42

标签: javascript jquery html events dom-events

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'>

我制作了一个具有其他功能的滑块,使用户可以轻松地将其设置在确切的中心。尝试一下,看看它如何立即在中间停止,但是如果您继续将其拖动到停止区域或以其他方式拖动,则可以将其滑动到任何位置。

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

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

我尝试使用mouseup / pointerup而不是change,但是在某些情况下它不起作用。您可以单击并按住滑块旋钮,然后将光标垂直移动到滑块区域之外,然后释放鼠标。由于光标在输入之外时释放了按钮,因此mouseup / pointerup事件不会触发。

即使用户未更改范围滑块,如何释放change事件?

2 个答案:

答案 0 :(得分:2)

通过点击

替换更改:-

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'>

答案 1 :(得分:1)

尝试此操作。在true的{​​{1}}中将变量设置为mousedown,并在control的{​​{1}}事件中检查它

mouseup
document