所以我正在尝试制作一个动画,根据滚动距离移动 div 并使其淡入淡出。我已经进行了转换,但不透明度更改似乎仅在桌面上有效。当从我的移动设备(iOS safari 和 iOS Firefox)查看它时,不透明度没有改变,我不明白为什么。在移动设备上滚动时,这些动画也会出现断断续续的情况,但在桌面上却不会。
@HostListener('window:scroll', ['$event'])
@HostListener('window:touchmove', ['$event'])
onScroll(): void {
if (this.isEffectActive) {
/* get position of the bottom of the component */
const introductionContainerBottomPos =
this.elementRef.nativeElement.offsetTop +
this.elementRef.nativeElement.offsetHeight;
const scrollPos = window.scrollY;
const distance =
introductionContainerBottomPos -
this.clamp(scrollPos, 0, introductionContainerBottomPos);
const val = this.lerp(0, 1, distance / introductionContainerBottomPos);
this.fadeValue = Math.round(val * 100) / 100;
window.requestAnimationFrame(() => {
this.container.nativeElement.style.opacity = this.fadeValue;
this.container.nativeElement.style.transform = `translateY(${this.getTranslation()}px)`;
this.container2.nativeElement.style.opacity = this.fadeValue;
this.container2.nativeElement.style.transform = `translateY(${this.getTranslation()}px)`;
});
}
}
有人知道更好的解决方案吗?
我尝试更改
filter: alpha
,但没有成功。我尝试内联不透明度,但这也不起作用。
will-change
属性添加到要设置动画的元素。.动画元素{ 将改变的:转变; }
2. Throttling:实现防抖功能来限制滚动事件处理程序。您可以使用像 lodash 这样的库或自己实现一个简单的去抖动功能。
import { Component, HostListener } from '@angular/core';
import { debounce } from 'lodash';
@Component({
selector: 'app-your-component',
templateUrl: './your-component.component.html',
styleUrls: ['./your-component.component.css']
})
export class YourComponent {
isEffectActive: boolean = true;
@HostListener('window:scroll', ['$event'])
onScroll = debounce(() => {
if (this.isEffectActive) {
// Your scroll handling logic here
}
}, 50); // Adjust the debounce delay as needed
}
3:优化不透明度变化: 使用 Angular 的动画模块来处理不透明度的变化。使用 Angular 的动画 DSL 在组件的 TypeScript 文件中定义动画。
import { Component, HostBinding } from '@angular/core';
import { trigger, transition, style, animate } from '@angular/animations';
@Component({
selector: 'app-your-component',
templateUrl: './your-component.component.html',
styleUrls: ['./your-component.component.css'],
animations: [
trigger('fadeAnimation', [
transition(':enter', [
style({ opacity: 0 }),
animate('300ms', style({ opacity: 1 })),
]),
transition(':leave', [
animate('300ms', style({ opacity: 0 })),
]),
]),
],
})
export class YourComponent {
@HostBinding('@fadeAnimation') fadeAnimation = true;
// Your other component logic
}
减少绘制区域:仅针对滚动事件处理程序中不透明度和变换更改所需的元素。
@HostListener('窗口:滚动', ['$event']) onScroll() { 如果(this.isEffectActive){ constscrollPos = window.scrollY; // 只更新必要元素的属性 this.container.nativeElement.style.transform =translateY(${this.getTranslation()}px); this.container2.nativeElement.style.transform =translateY(${this.getTranslation()}px); } }
这些方法应该有助于优化您的 Angular 代码,以获得更好的性能和跨不同设备和浏览器的兼容性。根据您的特定用例的需要调整值和设置。