在鼠标按下事件中连续更改范围输入元素的位置(单步执行)

时间:2018-04-24 00:36:10

标签: javascript jquery html css d3.js

我尝试使用范围输入元素构建滑块,该元素在点击,滚动或长按(连续按下)时移位1步。我有点击和滚动所需的逻辑,但是相同的逻辑似乎并不适用于鼠标按下事件(长按/连续按下)。

到目前为止我的代码(点击和鼠标按下):https://jsfiddle.net/ykun1k13/



var cur = 0;

d3.select('input')
  .on("input", function() {

    var threshold = d3.select(this).node().value;
    if (threshold > cur) {
      cur++
    } else if (threshold < cur) {
      cur--
    }
    d3.select(this).node().value = cur;

  });

d3.select('input')
  .on("mousedown", function() {
    var node1 = this;

    int = setInterval(function() {
      var threshold = d3.select(node1).node().value;
      if (threshold > cur) {
        cur++
      } else if (threshold < cur) {
        cur--
      }
      d3.select(node1).node().value = cur;
    }, 100)

  }).on('mouseup', function() {
    clearInterval(int);
  });
&#13;
.slider {
  -webkit-appearance: none;
  width: 400px;
  height: 8px;
  background: #d3d3d3;
  -webkit-transition: .2s;
  transition: opacity .2s;
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>
<p>
  <input class="slider" type="range" min="0" max="25" step="1" value="0" orient="vertical">
</p>
&#13;
&#13;
&#13;

我添加了一个鼠标向上事件和setInterval,以100ms的间隔连续跟踪鼠标,直到用户停止按下鼠标。

看起来像鼠标一样下来&#39;没有工作作为输入&#39;此处的事件和阈值的取值不是光标的位置,而是滑块的当前位置。

这可能是什么问题?我怎样才能连续/长按这个工作?

1 个答案:

答案 0 :(得分:0)

mousedownmouseup事件不应该持续触发,因为只有在按下或释放鼠标时才会触发它们。

有两个计时器,一个用于mousedown,另一个用于changeValue(),当mousedown时间长于500毫秒时,它会触发changeTimer计算值isIncreasing mouseup上的输入基础。 当var mouseTimer, changeTimer, cur = 0, threshold = 0, isIncreasing = false; d3.select('input') .on('input', function() { threshold = +this.value; if(+threshold > +cur) { cur++; isIncreasing = true; } else{ cur--; isIncreasing = false; } this.value = cur; }) d3.select('input') .on("mousedown", function() { var input = this; ClearTimeout(); mouseTimer = setTimeout(function() { changeValue(input); }, 500); }) d3.select(window) .on('mouseup', function() { ClearTimeout(); }); function changeValue(input){ changeTimer = setTimeout(function(){ if(isIncreasing){ cur++; cur = cur > threshold ? threshold : cur; } else { cur--; cur = cur < threshold ? threshold : cur; } input.value = cur; changeValue(input); }, 100) } function ClearTimeout() { clearTimeout(mouseTimer); clearTimeout(changeTimer); }时,请清除两个计时器。

&#13;
&#13;
.slider {
  -webkit-appearance: none;
  width: 400px;
  height: 8px;
  background: #d3d3d3;
  -webkit-transition: .2s;
  transition: opacity .2s;
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>
<p>
  <input class="slider" type="range" min="0" max="25" step="1" value="0" orient="vertical">
</p>
&#13;
./packages/mobile/
&#13;
&#13;
&#13;