各类距离计算(持续更新中...)

1.元素到可视窗口顶端的距离

$('XXX').offset().top-$(document).scrollTop();  //jq
XXXX.getBoundingClientRect().top   //js
// 举例应用,制作顶飘
//$(window).scrollTop() >=
$('XXX').offset() //元素超出视口高度,在视口的上方
 

2.判断元素是否在视口内

function isVisible($node) {
    var windowH = $(window).height(),// 窗口高度  视口高度
        scrollH = $(window).scrollTop(), // 滚动条高度
        $nodeOffsetH = $node.offset().top, // 元素距离文档顶部的高度
        $nodeHeight = $node.outerHeight(); // 元素自身高度 没用true 因此不包含margin
    if (!(scrollH > ($nodeOffsetH + $nodeHeight - 5) || (scrollH + windowH) < $nodeOffsetH)) {
        // 这里减5 为修正值 点击a 标签锚点定位时 有2px左右的误差
        return true
    } else {
        return false
    }

}     
//js版
const elementIsVisibleInViewport = (el, partiallyVisible = false) => { const { top, left, bottom, right } = el.getBoundingClientRect(); const { innerHeight, innerWidth } = window; return partiallyVisible ? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) && ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth)) : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth; }; // 事例 elementIsVisibleInViewport(el); // 需要左右可见 elementIsVisibleInViewport(el, true); // 需要全屏(上下左右)可以见

 

3.获取元素最终样式

与style的区别,style只会读取内联样式,

getComputedStyle会获取内联,外联,外部的最终样式

getComputedStyle(node).marginLeft;    //举例:获取元素的左边距

4.通过拖拽导航距离,计算居中的activeindex

//nav_box为导航子集的父级
//containerWidth 为nav_box的父级
function getChoose() {
    var left = getComputedStyle(nav_box).marginLeft;  //如果是scroll,可以改为scroll相关距离
    left = parseFloat(left) - containerWidth / 2;
    left = Math.abs(left);
    var i = left / config.optionWidth;
    i = Math.round(i);
    return config.options[i];
}

5.导航条根据activeindex动态,计算scrollLeft距离,使active居中

fuction  handleLeft(){           
            var item = $(navActiveCls);  //active
            var itemOffset = item.offset();  //针对元素和页面之间的横向偏移 , 纵向偏移用 position()
            var itemOffsetLeft = itemOffset.left + this.$navFather.scrollLeft();
            var centerLeft = (this.$nav.width() - item.width()) / 2;
            this.$navFather.stop().animate({
                scrollLeft: itemOffsetLeft - centerLeft
            })
        }

 

posted @ 2020-05-13 14:02  混名汪小星  阅读(289)  评论(0编辑  收藏  举报