【问题标题】:Angular: follow cursor has too much delay/lag角度:跟随光标有太多延迟/滞后
【发布时间】:2022-07-29 15:05:48
【问题描述】:

我想尝试做一个光标跟随移动的角度版本,但是鼠标移动不流畅,我该如何解决这个问题以及它的原因是什么?: https://stackoverflow.com/a/48756322/5152892

我的角度尝试: https://stackblitz.com/edit/angular-vnx9yd?file=src/app/app.component.ts

export class AppComponent {
  name = 'Angular';

  constructor(
    private el: ElementRef
  ) {}

  get tooltip() {
    return this.el.nativeElement.querySelector('.sites-circle');
  }

  enter(source: string) {
    this.tooltip.classList.add('show');
  }

  move(e: { pageX: number; pageY: number }) {
    const tooltipStyle = this.tooltip.style;

    tooltipStyle.left = e.pageX + 'px';
    tooltipStyle.top = e.pageY + 'px';
  }

  leave() {
    this.tooltip.classList.remove('show');
  }
}

CSS:

p {
  font-family: Lato;
}

.mouse-circle {
  position: absolute;
  border: solid 1px #ccc;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: white;
}
.show {
  opacity: 1 !important;
}

.sites-circle {
  z-index: 500;

  position: absolute;
  border: solid 1px #ccc;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: blue;
  pointer-events: none;
  transition-duration: 200ms;
  transition-timing-function: ease-out;
  transform: translate(-50%, -50%);
  opacity: 0;
}

.wrapper {
  height: 100vh;
  width: 100%;
}

HTML:

<div
  class="wrapper"
  (mouseenter)="enter()"
  (mousemove)="move($event)"
  (mouseleave)="leave()"
>
  <p>Start editing to see some magic happen :)</p>
  <div class="sites-circle">hello</div>
</div>

【问题讨论】:

  • 您链接的原始示例使用性能接近通用浏览器API的JQuery库,Angular只是不具备这种性能,它是一个缓慢的框架,有很多这样的挫败感像这样random one

标签: javascript angular


【解决方案1】:

有时最好使用 fromEvent rxjs 操作符来管理鼠标移动。这允许使用不同的运算符来不不断地发出事件

使用 Viewchild 获取元素

<div #mydiv class="show"
  class="wrapper"
  (mouseenter)="enter()"
  (mouseleave)="leave()"
>
  <div #tooltip class="sites-circle">hello</div>
</div>

@ViewChild('mydiv',{static:true}) div:ElementRef
@ViewChild('tooltip',{static:true}) tooltipEl:ElementRef

然后

  ngOnInit()
  {
    this.subscription=fromEvent(this.div.nativeElement,'mousemove').pipe(
        throttleTime(200,asyncScheduler,{ trailing: true }))
          .subscribe((e:any)=>{
             const tooltipStyle = this.tooltip.style;

             tooltipStyle.left = e.pageX + 'px';
             tooltipStyle.top = e.pageY + 'px';
             this.cont++;
    })
  }
  ngOnDestroy()
  {
    this.subscription.unsubscribe()
  }

在例如(参见stackblitz)我使用throttleTime 直到200 毫秒才发出新事件(您可以更改为100 或150)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-22
    • 2019-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-22
    • 1970-01-01
    相关资源
    最近更新 更多