javascript - 设置 onMouseDown 的最短执行时间

标签 javascript reactjs mouseevent

我的应用程序中有以下使用 Bootstrap 选项卡的弹出窗口:

enter image description here

反馈选项卡有几个子选项卡,我添加了功能,以便您可以在溢出的子选项卡(左侧和右侧)之间滚动。以下是我实现该功能的方法 (ReactJS):

this.feedbackScrollInterval = -1;    

_feedbackScroll = (id) => {
  let obj = ReactDOM.findDOMNode(this.refs.feedbackNav);
  let scrollWidth = obj.firstChild.scrollWidth;
  let offsetWidth = obj.firstChild.offsetWidth;
  if(this.feedbackScrollInterval==-1) {
    this.feedbackScrollInterval = setInterval(function(){
      if(id==1) {
        obj.firstChild.scrollLeft -= 5;
      } else {
        obj.firstChild.scrollLeft += 5;
      }
    }, 15);
  }
}

_clearFeedbackScroll = () => {
  clearInterval(this.feedbackScrollInterval);
  this.feedbackScrollInterval = -1;
}

以及按钮的标记:

<Button onMouseDown={this._feedbackScroll.bind(this, 1)} onMouseUp={this._clearFeedbackScroll}><Glyphicon glyph="chevron-left"></Glyphicon></Button>
<Button onMouseDown={this._feedbackScroll.bind(this, 2)} onMouseUp={this._clearFeedbackScroll}><Glyphicon glyph="chevron-right"></Glyphicon></Button>

上述按预期工作,但我想添加最短滚动时间。例如,如果我想要 250ms 的最短滚动时间,并且 mouseUp 事件在 150ms 后触发,我希望滚动继续进行另一个 100ms,直到达到最小值。

如何实现这一点? (没有 jQuery)

最佳答案

记录每次开始滚动操作的时间。

this.scrollStarted = Date.now();

然后当滚动完成时,检查持续时间。

let scrollFinished = Date.now();
let duration = scrollFinished - this.scrollStarted;

如果持续时间大于您的阈值 (250),则您可以清除该间隔。否则,请使用 setTimeout 适当延迟取消。

if(duration > 250) {
  // go ahead and cancel the scroll
} else {
  setTimeout(this._clearFeedbackScroll, 250 - duration);
}

关于javascript - 设置 onMouseDown 的最短执行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35719083/

相关文章:

javascript - 自调用函数调用其他函数的问题

javascript - react 滴答计时器

c++ - 实现自定义 QListWidgetItem?

javascript - 如何在将子div拖到另一个div时获取父div的id值

javascript - 需要 Javascript 正则表达式来匹配 URL 中的语言参数

reactjs - 弃用警告: Compilation. Assets 将来会被卡住,所有修改均已弃用

javascript - React Router VS 条件渲染

c# - 如何确定哪个鼠标按钮(例如 LeftButton)刚刚被释放?

javascript - 在javascript中模拟鼠标点击时如何设置目标属性?

javascript - 无法在 react 组件内以html打印javascript变量文本