js获取元素本身到顶部的高度

offsetTop方法会受父元素position定位影响,得到的值并不是想要的我们想用到的值,尤其是在遇到需要做动画的时候,我们更是会无从起手。

// 获取元素本身高度
function offSet(curEle) {
    // var totalLeft = 0;
    var totalTop = 0;
    var par = curEle.offsetParent;
    //首先把自己本身的相加
    // totalLeft += curEle.offsetLeft;
    totalTop += curEle.offsetTop;
    //累加父元素的相对上一个元素的距离值
    while (par) {
        if (navigator.userAgent.indexOf("MSIE 8.0") === -1) {
            //不是IE8我们才进行累加父级参照物的边框
            totalTop += par.clientTop;
            // totalLeft += par.clientLeft;
        }
        //把父级参照物的偏移相加
        totalTop += par.offsetTop;
        // totalLeft += par.offsetLeft;
        par = par.offsetParent;
    }
    // return { left: totalLeft, top: totalTop };
    return totalTop
}

以上方法可以获取dom元素准确到顶部的值。

我们首页动画class的控制且可以交给以下方法

// 获取元素
//box是获取的元素节点列表,满足条件动态添加想要的class
function setClass(box) {
    //滚动高度
    let visibleTop = window.scrollY;
    //滚动高度加上窗口可视高度
    let visibleBottom = visibleTop + document.documentElement.clientHeight;
    //遍历获取到的元素
    for (let i = 0; i < box.length; i++) {
        //获取元素顶部到页面顶部的距离
        let offsetTop = offSet(box[i]);
        //获取元素底部到页面距离顶部的距离
        let offsetBottom = offsetTop + box[i].offsetHeight;
        //判断offsetTop小于visibleBottom并且offsetBottom大于visibleTop则元素处在可视区域中
        if (offsetTop < visibleBottom && offsetBottom > visibleTop) {
            console.log(offsetTop)
            let classNames = box[i].getAttribute('class');
            if (classNames.indexOf('animation_left') > -1 && classNames.indexOf('animation_left_active') == -1) {
                box[i].classList.add("animation_left_active");
            } else if (classNames.indexOf('animation_right') > -1 && classNames.indexOf('animation_right_active') == -1) {
                box[i].classList.add("animation_right_active");
            } else if (classNames.indexOf('animation_opac') > -1 && classNames.indexOf('animation_opac_active') == -1) {
                box[i].classList.add("animation_opac_active");
            } else if (classNames.indexOf('animation_bottom') > -1 && classNames.indexOf('animation_bottom_active') == -1) {
                box[i].classList.add("animation_bottom_active");
            } else if (classNames.indexOf('animation_top') > -1 && classNames.indexOf('animation_top_active') == -1) {
                box[i].classList.add("animation_top_active");
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值