[英]How to add class on scroll in Angular
Just learning Angular again.刚刚又学习了 Angular。 Installed AngularCLI and am trying to add a class on scroll from what I had before using jquery.安装了 AngularCLI 并尝试从使用 jquery 之前的滚动中添加一个类。 Do I need to use [ngClass] to check a variable with window location?我是否需要使用 [ngClass] 来检查带有窗口位置的变量? I am trying to use @HostListener right now.我现在正在尝试使用@HostListener。
$(function () {
$(document).scroll(function () {
$nav.toggleClass('scrolled', $(this).scrollTop() > $nav.height());
});
});
$(function() {
$(document).scroll(function() {
var x = $(this).scrollTop();
if (x > 3300) {
$nav.removeClass('scrolled');
}
});
});
You can do something like this-你可以做这样的事情——
import { Component, HostListener, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(@Inject(DOCUMENT) private document: Document) { }
@HostListener('window:scroll', [])
onWindowScroll() {
if (document.body.scrollTop > 20 ||
document.documentElement.scrollTop > 20) {
document.getElementById('subTitle').classList.add('red');
document.getElementById('paragraph').classList.add('green');
}
}
name = 'Angular';
}
See live example here: https://stackblitz.com/edit/angular-changeclassonscroll在此处查看现场示例: https : //stackblitz.com/edit/angular-changeclassonscroll
You can use this code inside the class您可以在类中使用此代码
@HostListener('window:scroll', [])
onWindowScroll(event: Event) {
//set up the div "id=nav"
if (document.body.scrollTop > 3300 ||
document.documentElement.scrollTop > 3300) {
document.getElementById('nav').classList.add('scrolled');
}
else {
document.getElementById('nav').classList.remove('scrolled');
this.innerWidth = 'auto';
}
}
The above solutions work, but I think it's cleaner and more appropriate to utilize the framework as much as possible.上述解决方案有效,但我认为尽可能多地利用框架更清晰、更合适。
Typescript file:打字稿文件:
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
scrolled: boolean = false;
@HostListener("window:scroll", [])
onWindowScroll() {
this.scrolled = window.scrollY > 0;
}
}
Html:网址:
<div [ngClass]="{ className: scrolled }"></div>
add import on your typeScript file on top在您的打字稿文件上添加导入
{import {Component,HostListener,Directive,HostBinding,Input} from '@angular/core';}
then in app.components.ts for general scroll然后在 app.components.ts 中进行一般滚动
add添加
export class AppComponent { title = 'Tour of Heroes'; scrolled: boolean = false; @HostListener("window:scroll", []) onWindowScroll() { this.scrolled = window.scrollY > 0; } }
then add然后加
[ngClass]="{ 'scroll-add' : scrolled }" [ngClass]="{ 'scroll-add' : 滚动 }"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.