簡體   English   中英

當我完成拖動並且鼠標上升時,如何使我的可拖動 div 不運行 onClick function?

[英]How to make my draggable div not run the onClick function when I finish dragging and my mouse goes up?

所以我有一個可拖動的菜單 div。 現在它工作得幾乎完美,除了當我的鼠標上升時,它會觸發“onClick” function 觸發模式彈出。 我不希望這種情況發生。 我希望該模式僅在單擊時彈出,而不是在拖動后彈出。 但是當我的鼠標在拖動后上升時,我猜它是作為點擊事件觸發的。

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>
    );
  }
}

您可以測量自 <mouse.press> 和 <mouse.release> 以來經過的時間。
如果它不超過〜100ms,那么它可能是“點擊”而不是“拖動”。


您還可以實現 < mouse.position.change > 與一些 <Δ position > (~10px)
(因此按下按鈕時 cursor 的輕微移動不會注冊為“拖動”)。


如果將這兩個因素結合起來,確定是“點擊”還是“拖動”很容易。

我只需單擊一下,將onClick設置為null並設置onMouseUp以將onClick設置為您想要的任何功能:


<element onClick="" onMouseUp="this.onClick = <something>"></element>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM