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

时间:2018-08-03 15:15:49

标签: javascript html angular javascript-events draggable

问题

我有一个图像滑块,问题是拖动后会触发预览图像上的click事件。 我在this video

中展示了它

应有的行为

仅当用户未预先拖动时才触发click事件。

代码

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:

<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>

1 个答案:

答案 0 :(得分:0)

鼠标之后触发

点击。您的onMouseUp函数需要与onSmallItemClick结合使用。

此刻,发生 mousedown 并将isGrabbing设置为true,然后 mouseup 将其设置为false。因此,当 click 触发用户时,用户就无法“抓住”。

来自w3.org

  

这些事件的顺序是:

mousedown
mouseup
click