我正在使用Angular 4构建新网站,尝试重新创建一个效果:当一个div变为可见状态(屏幕向下滚动时),则可以触发一个Angular动画来从侧面滑动该div。
过去我能够使用Angular 4之外的jQuery实现这一点,但我想尝试使用本地的Angular 4动画创建相同的效果。
有人可以为我提供关于如何在div进入视口(即滚动到页面底部时)时触发动画的建议吗? 我已经编写了滑动动画,但我不知道如何在div稍后成为视口中可见的时候触发滚动以触发动画。
谢谢大家!
我正在使用Angular 4构建新网站,尝试重新创建一个效果:当一个div变为可见状态(屏幕向下滚动时),则可以触发一个Angular动画来从侧面滑动该div。
过去我能够使用Angular 4之外的jQuery实现这一点,但我想尝试使用本地的Angular 4动画创建相同的效果。
有人可以为我提供关于如何在div进入视口(即滚动到页面底部时)时触发动画的建议吗? 我已经编写了滑动动画,但我不知道如何在div稍后成为视口中可见的时候触发滚动以触发动画。
谢谢大家!
我创建了一个指令,当元素完全在视图内或其上边缘到达视图的上边缘时,立即发出事件。
这是一个 Plunker 示例:https://embed.plnkr.co/mlez1dXjR87FNBHXq1YM/
使用方法如下:
<div (appear)="onAppear()">...</div>
这是指令:
import {
ElementRef, Output, Directive, AfterViewInit, OnDestroy, EventEmitter
} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {Subscription} from 'rxjs/Subscription';
import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/operator/startWith';
@Directive({
selector: '[appear]'
})
export class AppearDirective implements AfterViewInit, OnDestroy {
@Output()
appear: EventEmitter<void>;
elementPos: number;
elementHeight: number;
scrollPos: number;
windowHeight: number;
subscriptionScroll: Subscription;
subscriptionResize: Subscription;
constructor(private element: ElementRef){
this.appear = new EventEmitter<void>();
}
saveDimensions() {
this.elementPos = this.getOffsetTop(this.element.nativeElement);
this.elementHeight = this.element.nativeElement.offsetHeight;
this.windowHeight = window.innerHeight;
}
saveScrollPos() {
this.scrollPos = window.scrollY;
}
getOffsetTop(element: any){
let offsetTop = element.offsetTop || 0;
if(element.offsetParent){
offsetTop += this.getOffsetTop(element.offsetParent);
}
return offsetTop;
}
checkVisibility(){
if(this.isVisible()){
// double check dimensions (due to async loaded contents, e.g. images)
this.saveDimensions();
if(this.isVisible()){
this.unsubscribe();
this.appear.emit();
}
}
}
isVisible(){
return this.scrollPos >= this.elementPos || (this.scrollPos + this.windowHeight) >= (this.elementPos + this.elementHeight);
}
subscribe(){
this.subscriptionScroll = Observable.fromEvent(window, 'scroll').startWith(null)
.subscribe(() => {
this.saveScrollPos();
this.checkVisibility();
});
this.subscriptionResize = Observable.fromEvent(window, 'resize').startWith(null)
.subscribe(() => {
this.saveDimensions();
this.checkVisibility();
});
}
unsubscribe(){
if(this.subscriptionScroll){
this.subscriptionScroll.unsubscribe();
}
if(this.subscriptionResize){
this.subscriptionResize.unsubscribe();
}
}
ngAfterViewInit(){
this.subscribe();
}
ngOnDestroy(){
this.unsubscribe();
}
}
Martin Cremer 的回答已经更新,适用于最新的 Rxjs 和 Angular 版本,希望能对您有所帮助。
import {
ElementRef, Output, Directive, AfterViewInit, OnDestroy, EventEmitter
} from '@angular/core';
import { Subscription } from 'rxjs';
import { fromEvent } from 'rxjs';
import { startWith } from 'rxjs/operators';
@Directive({
selector: '[appear]'
})
export class AppearDirective implements AfterViewInit, OnDestroy {
@Output() appear: EventEmitter<void>;
elementPos: number;
elementHeight: number;
scrollPos: number;
windowHeight: number;
subscriptionScroll: Subscription;
subscriptionResize: Subscription;
constructor(private element: ElementRef) {
this.appear = new EventEmitter<void>();
}
saveDimensions() {
this.elementPos = this.getOffsetTop(this.element.nativeElement);
this.elementHeight = this.element.nativeElement.offsetHeight;
this.windowHeight = window.innerHeight;
}
saveScrollPos() {
this.scrollPos = window.scrollY;
}
getOffsetTop(element: any) {
let offsetTop = element.offsetTop || 0;
if (element.offsetParent) {
offsetTop += this.getOffsetTop(element.offsetParent);
}
return offsetTop;
}
checkVisibility() {
if (this.isVisible()) {
// double check dimensions (due to async loaded contents, e.g. images)
this.saveDimensions();
if (this.isVisible()) {
this.unsubscribe();
this.appear.emit();
}
}
}
isVisible() {
return this.scrollPos >= this.elementPos || (this.scrollPos + this.windowHeight) >= (this.elementPos + this.elementHeight);
}
subscribe() {
this.subscriptionScroll = fromEvent(window, 'scroll').pipe(startWith(null))
.subscribe(() => {
this.saveScrollPos();
this.checkVisibility();
});
this.subscriptionResize = fromEvent(window, 'resize').pipe(startWith(null))
.subscribe(() => {
this.saveDimensions();
this.checkVisibility();
});
}
unsubscribe() {
if (this.subscriptionScroll) {
this.subscriptionScroll.unsubscribe();
}
if (this.subscriptionResize) {
this.subscriptionResize.unsubscribe();
}
}
ngAfterViewInit() {
this.subscribe();
}
ngOnDestroy() {
this.unsubscribe();
}
}
@Injectable()
export class AppearOnce implements AfterViewInit, OnDestroy {
appearedOnce: boolean;
elementPos: number;
elementHeight: number;
scrollPos: number;
windowHeight: number;
subscriptionScroll: Subscription;
subscriptionResize: Subscription;
constructor(private element: ElementRef, private cdRef: ChangeDetectorRef){}
onResize() {
this.elementPos = this.getOffsetTop(this.element.nativeElement);
this.elementHeight = this.element.nativeElement.clientHeight;
this.checkVisibility();
}
onScroll() {
this.scrollPos = window.scrollY;
this.windowHeight = window.innerHeight;
this.checkVisibility();
}
getOffsetTop(element: any){
let offsetTop = element.offsetTop || 0;
if(element.offsetParent){
offsetTop += this.getOffsetTop(element.offsetParent);
}
return offsetTop;
}
checkVisibility(){
if(!this.appearedOnce){
if(this.scrollPos >= this.elementPos || (this.scrollPos + this.windowHeight) >= (this.elementPos + this.elementHeight)){
this.appearedOnce = true;
this.unsubscribe();
this.cdRef.detectChanges();
}
}
}
subscribe(){
this.subscriptionScroll = Observable.fromEvent(window, 'scroll').startWith(null)
.subscribe(() => this.onScroll());
this.subscriptionResize = Observable.fromEvent(window, 'resize').startWith(null)
.subscribe(() => this.onResize());
}
unsubscribe(){
if(this.subscriptionScroll){
this.subscriptionScroll.unsubscribe();
}
if(this.subscriptionResize){
this.subscriptionResize.unsubscribe();
}
}
ngAfterViewInit(){
this.subscribe();
}
ngOnDestroy(){
this.unsubscribe();
}
}
@Component({
template: `
<div>
<div *ngIf="appearedOnce">...</div>
...
</div>
`
})
class MyComponent extends AppearOnceComponent {
...
}
super()
时它告诉我需要给它2个参数。 查看您使用的构造函数: private element: ElementRef,private cdRef:ChangeDetectorRef
。 应该是什么? - J Agustin Barrachina如果你想在特定组件中实现,有一个简单的方法:
最初的回答:
@ViewChild('chatTeaser') chatTeaser: ElementRef;
@HostListener('window:scroll')
checkScroll() {
const scrollPosition = window.pageYOffset + window.innerHeight;
if (this.chatTeaser && this.chatTeaser.nativeElement.offsetTop >= scrollPosition) {
this.animateAvatars();
}
}
在html中:
<div id="chat-teaser" #chatTeaser>
当元素顶部被滚动到时,该函数将被调用。如果您想要在完整的div可见时才调用函数,请将div高度添加到this.chatTeaser.nativeElement.offsetTop
中。
原始答案:最初的回答。
Martin Cremer的回答非常完美。
除非你想在使用Angular Universal的angular应用程序上运行此操作。
我已经修改了现有的被接受的答案,以便在ssr中运行。
import { Injectable } from '@angular/core';
export interface ICustomWindow extends Window {
__custom_global_stuff: string;
}
function getWindow (): any {
return window;
}
@Injectable({
providedIn: 'root',
})
export class WindowService {
get nativeWindow (): ICustomWindow {
return getWindow();
}
}
import { Directive, ElementRef, EventEmitter, HostListener, Output } from '@angular/core';
import { WindowService } from './window.service';
@Directive({
selector: '[appear]'
})
export class AppearDirective {
windowHeight: number = 0;
elementHeight: number = 0;
elementPos: number = 0;
@Output()
appear: EventEmitter<boolean>;
constructor(
private element: ElementRef,
private window: WindowService
) {
this.appear = new EventEmitter<boolean>();
}
checkVisible() {
if (this.elementPos < this.window.nativeWindow.scrollY + this.windowHeight) {
this.appear.emit(true);
this.appear.complete();
}
}
@HostListener('window:scroll', [])
onScroll() {
this.checkVisible();
}
@HostListener('window:load', [])
onLoad() {
this.windowHeight = (this.window.nativeWindow.innerHeight);
this.elementHeight = (this.element.nativeElement as HTMLElement).offsetHeight;
this.elementPos = (this.element.nativeElement as HTMLElement).offsetTop;
this.checkVisible();
}
@HostListener('window:resize', [])
onResize() {
this.windowHeight = (this.window.nativeWindow.innerHeight);
this.elementHeight = (this.element.nativeElement as HTMLElement).offsetHeight;
this.elementPos = (this.element.nativeElement as HTMLElement).offsetTop;
this.checkVisible();
}
}
onAppear() {
// TODO: do something
}
<!-- ... -->
<h2 (appear)="onAppear()">Visible</h2>
<!-- ... -->
有一个更新的API专门处理这个问题:IntersevtionObserver。使用它可以避免所有手动偏移计算和本地状态的保留。以下是使用此API的简单示例:
import { AfterViewInit, Directive, ElementRef, EventEmitter, OnDestroy, Output } from '@angular/core';
/**
* @description
* Emits the `appear` event when the element comes into view in the viewport.
*
*/
@Directive({
selector: '[visibleSpy]',
})
export class OnVisibleDirective implements AfterViewInit, OnDestroy {
@Output() appear = new EventEmitter<void>();
private observer: IntersectionObserver;
constructor(private element: ElementRef) {}
ngAfterViewInit() {
const options = {
root: null,
rootMargin: '0px',
threshold: 0,
};
this.observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
this.appear.next();
}
});
}, options);
this.observer.observe(this.element.nativeElement);
}
ngOnDestroy() {
this.observer.disconnect();
}
}
handleScrollEvent()
。item-grid.component.html
内部。<span [ngClass]="{hidden: curpage==maxpage}" (window:scroll)="handleScrollEvent()" (window:resize)="handleScrollEvent()" #loadmoreBtn (click)="handleLoadMore()">Load more</span>
在 item-grid.component.ts
文件内:
@ViewChild('loadmoreBtn') loadmoreBtn: ElementRef;
curpage: number;
maxpage: number;
ngOnInit() {
this.curpage = 1;
this.maxpage = 5;
}
handleScrollEvent() {
const { x, y } = this.loadmoreBtn.nativeElement.getBoundingClientRect();
if (y < window.innerHeight && this.maxpage > this.curpage) {
this.curpage++;
}
}