inner-scroll.js 2.46 KB
/**
 * 弹出层可以滚动,遮盖层禁止滚动插件
 *
 * @author liangzhifeng<zhifeng.liang@yoho.cn>
 * @date: 2016/02/22
 */

let $ = require('yoho-jquery');

function preventDefault(e) {
    e = e || window.event;
    e.preventDefault && e.preventDefault();
    e.returnValue = false;
}

function stopPropagation(e) {
    e = e || window.event;
    e.stopPropagation && e.stopPropagation();
    e.cancelBubble = false;
}

function innerScroll(e) {
    let delta = e.wheelDelta || e.originalEvent.wheelDelta || e.detail || 0,
        box = $(this).get(0);

    // 阻止冒泡到document
    // document上已经preventDefault
    stopPropagation(e);


    if ($(box).height() + box.scrollTop >= box.scrollHeight) {
        if (delta < 0) {
            preventDefault(e);
            return false;
        }
    }
    if (box.scrollTop === 0) {
        if (delta > 0) {
            preventDefault(e);
            return false;
        }
    }
}

function enableScroll($choseArea) {

    $choseArea.off('touchstart');
    $choseArea.off('touchmove');
    $choseArea.off('mousewheel');

    $(document).off('mousewheel', preventDefault);
    $(document).off('touchmove', preventDefault);
}
function disableScroll($choseArea) {
    enableScroll($choseArea);
    let startX, startY;

    // 内部可滚
    $choseArea.on('mousewheel', innerScroll);

    // 移动端touch重写
    $choseArea.on('touchstart', function(e) {
        startX = e.originalEvent.changedTouches[0].pageX;
        startY = e.originalEvent.changedTouches[0].pageY;
    });

    // 仿innerScroll方法
    $choseArea.on('touchmove', function(e) {
        let deltaX = e.originalEvent.changedTouches[0].pageX - startX,
            deltaY = e.originalEvent.changedTouches[0].pageY - startY;

        let box = $(this).get(0);

        e.stopPropagation();


        // 只能纵向滚
        if (Math.abs(deltaY) < Math.abs(deltaX)) {
            e.preventDefault();
            return false;
        }


        if ($(box).height() + box.scrollTop >= box.scrollHeight) {
            if (deltaY < 0) {
                e.preventDefault();
                return false;
            }
        }
        if (box.scrollTop === 0) {
            if (deltaY > 0) {
                e.preventDefault();
                return false;
            }
        }
    });

    $(document).on('mousewheel', preventDefault);
    $(document).on('touchmove', preventDefault);
}


exports.enableScroll = enableScroll;
exports.disableScroll = disableScroll;