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");
}
}
}
}