带Typecsript的自定义光标

时间:2019-04-03 10:32:41

标签: javascript html css angular typescript

我的意图是实现一个自定义游标,该游标是从这里获得的:

  

https://codepen.io/designcourse/pen/GzJKOE

我目前正在另一个使用Javascript的项目上工作。我的问题是我已经开始使用使用Typescript的Angular,但我不知道如何使用Typescript实现此光标。有什么建议吗?

<div class="cursor"></div>
.cursor {
  width: 20px;
  height: 20px;
  border: 1px solid white;
  border-radius: 50%;
  position: absolute;
  transition-duration: 200ms;
  transition-timing-function: ease-out;
  animation: cursorAnim .5s infinite alternate;
  pointer-events: none;
}

.cursor::after {
  content: "";
  width: 20px;
  height: 20px;
  position: absolute;
  border: 8px solid gray;
  border-radius: 50%;
  opacity: .5;
  top: -8px;
  left: -8px;
  animation: cursorAnim2 .5s infinite alternate;
}

@keyframes cursorAnim {
  from {
    transform: scale(1);
  }
  to {
    transform: scale(.7);
  }
}

@keyframes cursorAnim2 {
  from {
    transform: scale(1);
  }
  to {
    transform: scale(.4);
  }
}

@keyframes cursorAnim3 {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(3);
  }
  100% {
    transform: scale(1);
    opacity: 0;
  }
}

.expand {
  animation: cursorAnim3 .5s forwards;
  border: 1px solid red;
}
        const cursor = document.querySelector('.cursor');

        document.addEventListener('mousemove', e => {
            cursor.setAttribute("style", "top: "+(e.pageY - 10)+"px; left: "+(e.pageX - 10)+"px;")
        })

        document.addEventListener('click', () => {
            cursor.classList.add("expand");

            setTimeout(() => {
                cursor.classList.remove("expand");
            }, 500)
        })

1 个答案:

答案 0 :(得分:0)

首先使用@HostListener

监听事件
  1. 点击事件

    使用[ngClass]并将expand类绑定为:[ngClass]="{'expand':expand}"

  2. 鼠标移动事件

    使用[style.top][style.left]并用$event的{​​{1}}绑定值

See working code

TS:

mousemove

HTML

    export class AppComponent  {

      top:any;
      left:any;
      expand=false;

      constructor() {}


      @HostListener('document:click', ['$event'])
      onClick($event) {
         this.expand=true;
         setTimeout(() => {
          this.expand=false;
         }, 500)
     }

    @HostListener('document:mousemove', ['$event'])
      onMousemove($event) {
        this.top=($event.pageY - 10)+ "px";
        this.left= ($event.pageX - 10)+ "px";
     }


    }

使用与发布相同的CSS