问题
I have this directive to do something when the mouseenter
event is triggered on an element. But when I drag the mouse fast, over the elements some elements are getting skipped without triggering the mouseenter
event.
I actually want to highlight a range of cells of a grid when the mouse moves. I have added this directive to the template of the grid cell.
@Directive({
// tslint:disable-next-line:directive-selector
selector: '[appRangeSelector]'
})
export class RangeSelectorDirective {
@Input() public selectorParams: any;
public isSelected = false;
constructor(private elRef: ElementRef,
private renderer: Renderer2) { }
@HostListener('mouseenter', ['$event']) public onMouseEnter(e) {
if (e.buttons === 1 || e.buttons === 3) {
if (!this.isSelected) {
console.log('selected');
this.renderer.setStyle(this.elRef.nativeElement, 'background', 'blue');
this.isSelected = true;
} else {
console.log('deselected');
this.renderer.setStyle(this.elRef.nativeElement, 'background', 'unset');
this.isSelected = false;
}
}
}
}
I need to select the range when the user select the cell range in any speed. Any help about this is appreciated.
回答1:
Operating system only update mouse position at a certain interval, and continuous movement is not garanteed.
If you want to be bulletproof, you might need to listen to mousemove event, calculate trajectory, and check if it intersect with any of your element. However, I'm afraid that this can be somewhat heavy, so you better benchmark it first.
来源:https://stackoverflow.com/questions/53187329/mouseenter-event-is-skipping-elements