简体   繁体   中英

onMouseUp and onClick events conflicting

i have a scrollbar and i want to scroll by 40px when clicking on a button , and when holding that same button, it scrolls continuously

So i used onClick event for a single walk of 40px and i used onMouseDown and onMouseUp for the continuous scrolling effect

The problem is that onMouseUp fires the onClick event too .. so the scroll bar moves for 40px more when we release the mouse button and this gives a bad effect

i used setInterval inside onMouseDown :

clickScroll = () => {
    const slider : HTMLElement = this.state.scrollRef.current;
    slider.scrollBy(40, 0)
}

holdScroll = (type : string) => {   
    const slider : HTMLElement = this.state.scrollRef.current;
    this.setState({
        interval : setInterval(() => {
            slider.scrollBy(walk, 0)
        }, 100)
    })
}

stopHoldScroll = () => {
    clearInterval(this.state.interval);
}

And my button :

<Button onClick={this.clickScroll}
  onMouseDown={this.holdScroll}
  onMouseUp={this.stopHoldScroll}>
      <span className="fas fa-chevron-right" /> 
</Button>

Any idea about how to dissociate these 2 differents effects ? thanks

I finally found a way to do it ! thanks to Jacques for the idea

we can combine setTimeout and setInterval to create a small difference between a click and holding button The boolean can indicate us inside onMouseUp if we were holding or just clicking ! it turns true after 300ms of holding, if not then it's just a click

    const slider : HTMLElement = this.state.refs.current;
    scrollHold = () => {
        this.setState({
            timer: setTimeout(() => {
                this.setState({
                    interval : setInterval(() => {
                        slider.scrollBy(8, 0)
                    }, 20),
                    holded: true
                })
            },300)
        })
    }
    stopScroll = () => {
        if (!this.state.holded){
            this.state.current.scrollBy(40, 0)
        }
        clearTimeout(this.state.timer)
        clearInterval(this.state.interval);
        this.setState({ holded: false })
    }
<Button 
  onMouseDown={this.scrollHold}
  onMouseUp={this.stopScroll}>
      <span className="fas fa-chevron-right" /> 
</Button>             

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM