简体   繁体   English

区分“正常”点击和拖动后点击

[英]Differentiate between “Normal” Click and Click after Dragging

Problem 问题

I have an image slider, and the issue is, that the click event on a preview image is fired after dragging. 我有一个图像滑块,问题是拖动后会触发预览图像上的click事件。 I showcased it in this video 我在这个视频中展示了它

Supposed Behavior 假设行为

The click event should only be triggered when the user did not drag beforehand. 仅当用户未预先拖动时才应触发click事件。

Code

isGrabbing: boolean = false;
    startX: number;
    startXPerc: number;
    translateX: number = 0;
    diffPerc: number;

    @ViewChild('slider') slider;

    onMouseDown(e: MouseEvent): void {
        const pageX = e.pageX;
        this.isGrabbing = true;
        this.startX = pageX - this.slider.nativeElement.offsetLeft;
        this.startXPerc = this.translateX;
    }

    onMouseUp(e: MouseEvent): void {
        this.isGrabbing = false;
    }

    onMouseMove(pageX: number): void {
        if (!this.isGrabbing) return;
        const x = pageX - this.slider.nativeElement.offsetLeft;
        const diff = this.startX - x;
        this.diffPerc = 100 * diff / this.slider.nativeElement.offsetWidth;
        this.translateX = this.startXPerc - this.diffPerc;
    }

    get translateXValue(): string {
        return `translateX(${this.translateX}%)`
    }

    onSmallItemClick(i: number): void {
        // this line should only be triggered
        // if the user did not drag beforehand
        this.animate(i * -100);
    }

Html: HTML:

<div
    class="small-slider-container"
    (mousedown)="onMouseDown($event)"
    (mousemove)="onMouseMove($event)"
    (mouseup)="onMouseUp($event)"
    #slider
>
    <div
        class="small-slider"
        [style.transform]="smallTranslateXValue"
        [class.grabbing]="smallSliderGrabbing"
        [class.grab]="!smallSliderGrabbing"
    >
        <div
            class="item"
            *ngFor="let i of images; let j = index"
            [style.left]="j * 10 + '%'"
            (click)="onSmallItemClick(j)"
        >
            <div class="content">
                <img src="{{ i }}">
            </div>
        </div>
    </div>
</div>

click is triggered after mouseup . mouseup之后触发点击 Your onMouseUp function needs to be combined with onSmallItemClick . 您的onMouseUp函数需要与onSmallItemClick结合使用。

At the moment, mousedown happens and sets isGrabbing to true, then mouseup sets it to false. 此刻,发生mousedown并将isGrabbing设置为true,然后mouseup将其设置为false。 So, by the time click fires the user is 'not' grabbing. 因此,当点击触发时,用户就无法“抓住”。

From w3.org : 来自w3.org

The sequence of these events is: 这些事件的顺序是:

 mousedown mouseup click 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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