当我完成拖动并且鼠标上升时,如何使我的可拖动div不运行onClick函数?

问题描述 投票:0回答:2

所以我有一个可拖动的div菜单。现在,它几乎可以正常工作,除了当我的鼠标上升时,它会触发触发弹出模式的“ onClick”功能。我不希望那样发生。我希望该模式仅在单击时弹出,而不在拖动后弹出。但是,当我的鼠标在拖动后上升时,我想它是作为单击事件触发的。

jsfiddle:https://jsfiddle.net/annahisenberg/ft10ersb/1/

代码:

constructor(props) {
    super(props);
    this.state = {
      x: this.props.x,
      y: this.props.y,
      showMoreOptionsPopup: false,
      showHelpModal: false
    };

    this.reff = React.createRef();
  }

  componentDidMount() {
    this.pos1 = 0;
    this.pos2 = 0;
    this.pos3 = 0;
    this.pos4 = 0;
  }

  dragMouseDown = e => {
    e.preventDefault();
    this.pos3 = e.clientX;
    this.pos4 = e.clientY;
    document.onmouseup = this.closeDragElement;
    document.onmousemove = this.elementDrag;
  };

  elementDrag = e => {
    e.preventDefault();
    this.pos1 = this.pos3 - e.clientX;
    this.pos2 = this.pos4 - e.clientY;
    this.pos3 = e.clientX;
    this.pos4 = e.clientY;
    this.setState({
      y: this.reff.current.offsetTop - this.pos2 + "px",
      x: this.reff.current.offsetLeft - this.pos1 + "px"
    });
  };

  closeDragElement = () => {
    document.onmouseup = null;
    document.onmousemove = null;
  };

  showMoreOptionsPopup = () => {
    this.setState({
      showMoreOptionsPopup: !this.state.showMoreOptionsPopup
    });
  };

render() {
    return (
      <div>
        {this.state.showMoreOptionsPopup && (
          <div
            id="more_options_popup"
            style={{
              left: this.reff.current.offsetLeft - 170 + "px",
              top: this.reff.current.offsetTop - 130 + "px"
            }}
          >
           Help Doc
          </div>
        )}

        <div
          id="more_options_button"
          onClick={this.showMoreOptionsPopup}
          style={{ left: this.state.x, top: this.state.y }}
          onMouseDown={this.dragMouseDown}
          ref={this.reff}
        >
          {this.state.showMoreOptionsPopup ? (
            <Icon name="close" />
          ) : (
            <Icon name="menu" />
          )}
        </div>
      </div>
    );
  }
}
javascript reactjs drag-and-drop
2个回答
0
投票

您可以测量自开始经过的时间。如果时间不超过100ms,则可能是“单击”而不是“拖动”。


您还可以使用(〜10px)来实现(这样,按下按钮时光标的轻微移动将不会注册为“拖动”。)>


如果将这两个因素结合在一起,则很容易确定是“单击”还是“拖动”。


0
投票

我只要单击一下,将onClick设置为null,然后将onMouseUp设置为将onClick设置为所需的任何功能:

© www.soinside.com 2019 - 2024. All rights reserved.