移动端优化(滚动穿透)

 var stopScrollThrough = {
        pos: {
            x: 0,
            y: 0
        },
        stopEvent: function (e) {
            e.preventDefault()
            e.stopPropagation()
        },
        startPosition: function (e) {
            stopScrollThrough.pos.x = e.touches[0].clientX;
            stopScrollThrough.pos.y = e.touches[0].clientY;
        },
        watchTouchMove: function (e) {
            var target = e.target,
                parents = $(target).parents('.mobileScrollBox'),
                el = null;
            if (target.classList.contains('.mobileScrollBox')) {
                el = target;
            } else if (parents.length) {
                el = parents[0];
            } else {
                return stopScrollThrough.stopEvent(e);
            }
            var dx = e.touches[0].clientX - stopScrollThrough.pos.x,
                dy = e.touches[0].clientY - stopScrollThrough.pos.y,
                direction = dy > 0 ? '10' : '01',
                scrollTop = el.scrollTop,
                scrollHeight = el.scrollHeight,
                offsetHeight = el.offsetHeight,
                isVertical = Math.abs(dx) < Math.abs(dy),
                status = '11';
            if (scrollTop == 0) {
                status = offsetHeight >= scrollHeight ? '00' : '01'
            } else if (scrollTop + offsetHeight >= scrollHeight) {
                status = '10'
            }
            if (status !== '11' && isVertical && !(parseInt(status, 2) & parseInt(direction, 2))) {
                return stopScrollThrough.stopEvent(e);
            }
        },
        startStopScroll: function (e) {
            document.addEventListener('touchstart', stopScrollThrough.startPosition, { passive: false });
            document.addEventListener('touchmove', stopScrollThrough.watchTouchMove, { passive: false });
        },
        removeStopScroll: function (e) {
            document.removeEventListener('touchstart', stopScrollThrough.startPosition, { passive: false });
            document.removeEventListener('touchmove', stopScrollThrough.watchTouchMove, { passive: false });
        }
    }

 

posted @ 2020-05-13 17:30  ken丶123  阅读(194)  评论(0编辑  收藏  举报