【问题标题】:Blurry lazy image loading by IntersectionObserverIntersectionObserver 模糊延迟图像加载
【发布时间】:2021-02-13 10:46:53
【问题描述】:

我为延迟加载图像实现了一个指令,如下所示效果很好:

@Directive({
  selector: "[appLazyLoad]"
})
export class LazyLoadDirective implements AfterViewInit {
  @HostBinding("attr.src") srcAttr = null;
  @Input() src: string;

  constructor(private el: ElementRef) {}

  ngAfterViewInit() {
    this.canLazyLoad() ? this.lazyLoadImage() : this.loadImage();
  }

  private canLazyLoad() {
    return window && "IntersectionObserver" in window;
  }

  private lazyLoadImage() {
    const obs = new IntersectionObserver(entries => {
      entries.forEach(({ isIntersecting }) => {
        if (isIntersecting) {
          this.loadImage();
          obs.unobserve(this.el.nativeElement);
        }
      });
    });
    obs.observe(this.el.nativeElement);
  }

  private loadImage() {
    this.srcAttr = this.src;
  }
}

用法示例:

<img [src]="imageUrl" appLazyLoad />

现在我希望照片先模糊然后然后变清晰

【问题讨论】:

标签: angular angular-directive intersection-observer


【解决方案1】:

我认为您应该添加默认模糊的样式,然后在加载后添加样式以清除模糊: 我在stackblitz为你做例子

.image {
  display: block;
  min-height: 20rem; /* layout hack */
  background: #fff center center no-repeat;
  background-size: cover;
  filter: blur(3px); /* blur the lowres image */
}
.image.is-loaded {
  filter: none; /* remove the blur on fullres image */
  transition: filter 1s;
}

指令:

@Directive({
    selector: "[appLazyLoad]"
})
export class LazyLoadDirective implements AfterViewInit {

    @HostBinding("attr.src") srcAttr = null;
    @Input() src: string;

    constructor(private renderer: Renderer2,private  el: ElementRef) {
        renderer.addClass(el.nativeElement, 'image');//added
    }

    ngAfterViewInit() {
        this.canLazyLoad() ? this.lazyLoadImage() : this.loadImage();
    }

    private canLazyLoad() {
        return window && "IntersectionObserver" in window;
    }

    private lazyLoadImage() {
        const obs = new IntersectionObserver(entries => {
            entries.forEach(({ isIntersecting }) => {
                if (isIntersecting) {
                    this.loadImage();
                    obs.unobserve(this.el.nativeElement);
                }
            });
        });
        obs.observe(this.el.nativeElement);
    }
    
    private loadImage() {
        this.srcAttr = this.src;
        this.renderer.addClass(this.el.nativeElement, 'is-loaded'); //added
    }
}

【讨论】:

  • 其实我需要对原图进行模糊处理
猜你喜欢
  • 1970-01-01
  • 2023-02-15
  • 1970-01-01
  • 2013-10-24
  • 2021-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多