2017-07-19 1 views
23

Je crée une page Web ayant des divs largeur/hauteur de page complète. En faisant défiler vers le bas, j'ai deux types de méthodes.Angular 4 - Animation par défilement

Faire défiler sur Cliquez

//HTML 
<a (click)="goToDiv('about')"></a> 

//JS 
    goToDiv(id) { 
     let element = document.querySelector("#"+id); 
     element.scrollIntoView(element); 
     } 

Faire défiler sur HostListener

@HostListener("window:scroll", ['$event']) 
    onWindowScroll($event: any): void { 
    this.topOffSet = window.pageYOffset; 
    //window.scrollTo(0, this.topOffSet+662); 
    } 

1. Comment ajouter un effet d'animation de défilement?

Tout comme:

$('.scroll').on('click', function(e) { 
    $('html, body').animate({ 
     scrollTop: $(window).height() 
    }, 1200); 
}); 

2. Et comment utiliser HostListener pour défiler jusqu'à la prochaine div?

+0

Je pense que c'est la solution ici [https://stackoverflow.com/questions/38748572/scroll-event-on-hostlistener](https://stackoverflow.com/questions/38748572/scroll-event-on-hostlistener –

+0

@ObaidulHaque 'HostListener' fonctionne correctement. Vous ne savez pas comment ajouter une animation. –

+0

Utilisez l'animation CSS dans les fonctions que vous appelez dans le port d'écoute de l'hôte. Bon guide ici: https://css-tricks.com/aos-css-driven-scroll-animation-library/ –

Répondre

8

Celui-ci est amusant. La solution, comme avec la plupart des choses angulaires 2, est observables.

getTargetElementRef(currentYPos: int): ElementRef { 
     // you need to figure out how this works 
     // I can't comment much on it without knowing more about the page 
     // but you inject the host ElementRef in the component/directive constructor and use normal vanillaJS functions to find other elements 
    } 
    //capture the scroll event and pass to a function that triggers your own event for clarity and so you can manually trigger 
    scrollToSource: Subject<int> = new Subject<int>(); 
    @HostListener("window:scroll", ['$event']) 
    onWindowScroll($event: any): void { 
    var target = getTargetElementRef(window.pageYOffset); 
    this.scrollTo(target); 
    } 

    scrollTo(target: ElementRef): void { 
    // this assumes you're passing in an ElementRef, it may or may not be appropriate, you can pass them to functions in templates with template variable syntax such as: <div #targetDiv>Scroll Target</div> <button (click)="scrollTo(targetDiv)">Click To Scroll</button> 
    this.scrollToSource.next(target.nativeElement.offsetTop); 
    } 

    //switch map takes the last value emitted by an observable sequence, in this case, the user's latest scroll position, and transforms it into a new observable stream 
    this.scrollToSource.switchMap(targetYPos => { 
     return Observable.interval(100) //interval just creates an observable stream corresponding to time, this emits every 1/10th of a second. This can be fixed or make it dynamic depending on the distance to scroll 
      .scan((acc, curr) => acc + 5, window.pageYOffset) // scan takes all values from an emitted observable stream and accumulates them, here you're taking the current position, adding a scroll step (fixed at 5, though this could also be dynamic), and then so on, its like a for loop with +=, but you emit every value to the next operator which scrolls, the second argument is the start position 
      .do(position => window.scrollTo(0, position)) /// here is where you scroll with the results from scan 
      .takeWhile(val => val < targetYPos); // stop when you get to the target 
    }).subscribe(); //don't forget! 

Avec un clic, c'est facile à utiliser. Vous venez de lier scrollTo à un clic

Cela ne fonctionne que pour faire défiler dans une direction, Cependant, cela devrait vous aider à démarrer. Vous pouvez rendre la numérisation plus intelligente afin de la soustraire si vous avez besoin de monter, et utiliser à la place une fonction dans takeWhile qui détermine la condition de terminaison correcte en fonction de si vous montez ou descendez.

+0

Votre code a bien fonctionné pour moi, merci. Juste pensé à ajouter, pour angulaire 4> vous devez utiliser l'importation '' rxjs/add/operator/switchMap '; 'sinon vous devrez faire face à la question" ..switchMap n'est pas une fonction ". – KeaganFouche