我想向模板html中的html元素添加视差效果。我已经编写了执行此操作的代码,但是不确定每次页面滚动时在何处实现它。
let pos = document.body.scrollTop;
document.getElementById('parallex').style.marginTop = '-' + pos + 'px';
我尝试将其添加到ngDoCheck函数中,但是仅工作了一次。怎么做?
答案 0 :(得分:0)
如果我了解你。
您需要使用
window.onscroll() 像这样
window.onscroll = function (e) {
// called when the window is scrolled.
let pos = document.body.scrollTop;
document.getElementById('parallex').style.marginTop = '-' + pos + 'px';
}
答案 1 :(得分:0)
Angular 为此提供了主机侦听器。最佳实践是使用 ViewChild 访问 html 元素,使用 renderer2 更新属性
<块引用>HTML
onBindViewHolder
<块引用>
TS
<span #parallex class="parallex">dfd</span>
查看 this stackblitz 以获取工作演示。