• html/css 滚动到元素位置,显示加载动画


    每次滚动到元素时,都显示加载动画,如何添加? 

    元素添加初始参数

    以上图中的动画为例,添加俩个左右容器,将内容放置在容器内部。

    添加初始数据,默认透明度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);
    }
    }

    https://www.tmojm.com 创业加盟网

    触发动画

    页面加载/刷新触发 - 在componentDidMount中执行

    页面滚动时触发 - 在componentDidMount、componentWillUnmount添加监听/注销页面滚动的事件

    校验当前滚动高度与元素的位置差异:

    window.pageYOffset(滚动距离) + windowHeight(窗口高度) > leftElement.offsetTop (元素的相对位置)+ parentOffsetTop(父元素的相对位置) + 200

    1. 真正的滚动视觉位置 - window.pageYOffset(滚动距离) + windowHeight(窗口高度)
    2. 元素距离顶部的高度 - 这里使用了leftElement.offsetTop + parentOffsetTop,原因是父容器使用了absolute绝对定位。如果是正常布局的话,使用元素当前的位置leftElement.offsetTop即可
    3. 额外添加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" //隐藏动画
    }
    }
  • 相关阅读:
    哈夫曼树
    MongoDB
    Node.js 搭建Web
    Node.js
    HDFS编程
    scp
    MapRecude
    级数
    (转)MySQL百万级数据库优化
    ssh
  • 原文地址:https://www.cnblogs.com/xiaonian8/p/15065699.html
Copyright © 2020-2023  润新知