这个效果就是锤子科技官网的那个效果,滴滴滴传送门,效果有一点偏差,总体还行。
说一下,实现这个的难点在哪
用原生写的话,大家都会写,但是对于初学angular的人来说,比如我,决定写的时候我整个人是懵的,原生我会写,可是让我用angular写,我不知道从何写起。。。
运用angular的指令,把这个效果包装在一个指令里,下次想用简直不要太方便凹(在需要的地方添个指令就ok拉),
- 在angular指令里操作鼠标事件、传递参数,
- 怎样获取鼠标操作对象的event对象呢,和原生一样
怎样获取并操作对象的各种属性呢
做这个的时候我还不知道。。。查资料看博客。。才知道是这个写的
1. @HostListener('mousemove') onMouseMove(para) {}
2. @HostListener('mousemove') onMouseMove(para) {
let e= para ||window.event;
}
3.
export class DirectivesDirective {
constructor(private el: ElementRef) {
}
@HostListener('mousemove') onMouseMove(para) {
let e= para ||window.event;
let divTop = this.el.nativeElement.offsetTop;
...
}
}
了解了上面的基本结构,就可以完成这个效果了,毕竟逻辑什么的都是一样的。
直接贴代码
import {Directive, ElementRef, HostListener} from '@angular/core';
@Directive({
selector: '[appDirectives]'
})
export class DirectivesDirective {
// public el;
private distance = 50;
private rotationMultiple = 0.1
constructor(private el: ElementRef) {
this.distance = 50;
this.rotationMultiple = 0.1
}
@HostListener('mousemove') onMouseMove(para) {
let e= para ||window.event;
let divTop = this.el.nativeElement.offsetTop;
let divLeft = this.el.nativeElement.offsetLeft;
let divWidth = this.el.nativeElement.offsetWidth;
let divHeight =this.el.nativeElement.offsetHeight;
if(e.clientX < divWidth/2 && e.clientY > divHeight/2 || e.clientX > divWidth/2 && e.clientY > divHeight/2) {
// 3.4
let pctX =(((e.clientX - divLeft)/ divWidth) - 0.5);
let pctY = -(((e.clientY - divTop)/ divHeight) - 0.3);
this.animate(pctX, pctY, this.rotationMultiple, this.distance);
}
if(e.clientX < divWidth/2 && e.clientY < divHeight/2 || e.clientX > divWidth/2 && e.clientY < divHeight/2) {
// 1.2
let pctX =((e.clientX - divLeft)/ divWidth) - 0.7;
let pctY = ((e.clientY - divTop)/ divHeight) - 0.5;
this.animate(pctX, pctY, this.rotationMultiple, this.distance);
}
}
private animate(pctX: number, pctY: number, rotationMultiple: number, distance: number) {
let rotateX = pctY * rotationMultiple * -180;
let rotateY = pctX * rotationMultiple * 180;
this.el.nativeElement.style.transform = ' rotateX(' + rotateX + 'deg' + ')' + ' rotateY(' + rotateY + 'deg'+ ')';
}
}
哇 这个截图工具有点迷醉,真卡,
这篇博客讲述了作者如何使用Angular4实现类似锤子科技官网的鼠标悬停3D倾斜效果。难点在于将原生JavaScript效果转换为Angular指令,包括处理鼠标事件、传递参数以及操作对象属性。通过学习和实践,作者最终成功封装了一个方便复用的指令。

1602

被折叠的 条评论
为什么被折叠?



