html/css 滚动到元素位置,显示加载动画
manongba · 368浏览 · 发布于2020-06-19
每次滚动到元素时,都显示加载动画,如何添加?
元素添加初始参数
以上图中的动画为例,添加俩个左右容器,将内容放置在容器内部。
添加初始数据,默认透明度0、左右分别移动100px。
//左侧容器 .item-leftContainer { opacity: 0; transform: translateX(-100px); } //右侧容器 .item-rightContainer { opacity: 0; transform: translateX(100px); }
添加动画数据
在less中添加动画数据。这里只设置了to,也可以省略第1步中的初始参数设置而在动画里设置from。
执行后,透明度由0到1,俩个容器向中间移动100px回到原处。
//动画 @keyframes showLeft { to { opacity: 1; transform: translateX(0px); } } @keyframes showRight { to { opacity: 1; transform: translateX(0px); } } @keyframes hideLeft { to { opacity: 0; transform: translateX(-100px); } } @keyframes hideRight { to { opacity: 0; transform: translateX(100px); } }
触发动画
页面加载/刷新触发 - 在componentDidMount中执行
页面滚动时触发 - 在componentDidMount、componentWillUnmount添加监听/注销页面滚动的事件
校验当前滚动高度与元素的位置差异:
window.pageYOffset(滚动距离) + windowHeight(窗口高度) > leftElement.offsetTop (元素的相对位置)+ parentOffsetTop(父元素的相对位置) + 200
真正的滚动视觉位置 - window.pageYOffset(滚动距离) + windowHeight(窗口高度)
元素距离顶部的高度 - 这里使用了leftElement.offsetTop + parentOffsetTop,原因是父容器使用了absolute绝对定位。如果是正常布局的话,使用元素当前的位置leftElement.offsetTop即可
额外添加200高度,是为了优化视觉体验。当超出200高度时才触发动画
当页面滚动到下方,触发显示动画;当页面重新滚动到上方,触发隐藏动画。
componentDidMount() { this.checkScrollHeightAndLoadAnimation(); window.addEventListener('scroll', this.bindHandleScroll); } componentWillUnmount() { window.removeEventListener('scroll', this.bindHandleScroll); } bindHandleScroll = (event) => { this.checkScrollHeightAndLoadAnimation(); } checkScrollHeightAndLoadAnimation() { const windowHeight = window.innerHeight; let parentEelement = document.getElementById("softwareUsingWays-container") as HTMLElement; const parentOffsetTop = parentEelement.offsetTop; let leftElement = (parentEelement.getElementsByClassName("item-leftContainer") as HTMLCollectionOf<HTMLElement>)[0]; if (window.pageYOffset + windowHeight > leftElement.offsetTop + parentOffsetTop + 200) { leftElement.style.animation = "showLeft .6s forwards" //添加动画 } else { leftElement.style.animation = "hideLeft 0s forwards" //隐藏动画 } let rightElement = (parentEelement.getElementsByClassName(".item-rightContainer") as HTMLCollectionOf<HTMLElement>)[0]; if (window.pageYOffset + windowHeight > rightElement.offsetTop + parentOffsetTop + 200) { rightElement.style.animation = "showRight .6s forwards" //添加动画 } else { rightElement.style.animation = "hideRight 0s forwards" //隐藏动画 } }
相关推荐
RN开发环境的npm私库本地debug调试
manongba · 698浏览 · 2019-05-09 17:03:46
你不知道的浏览器渲染原理
追忆似水年华 · 1373浏览 · 2019-05-09 22:47:56
基于iview的router常用控制方式
追忆似水年华 · 999浏览 · 2019-06-03 10:39:21
编程小知识之 JavaScript 文件读取
manongba · 717浏览 · 2019-06-10 09:16:16
浏览器关闭后,Session会话结束了么?
追忆似水年华 · 907浏览 · 2019-06-13 09:39:50
分类专栏
最新发布
最热排行
0评论