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

var $ = 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) {
    var 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 disableScroll($choseArea) {
    var 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) {
        var deltaX = e.originalEvent.changedTouches[0].pageX - startX,
            deltaY = e.originalEvent.changedTouches[0].pageY - startY;

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

function enableScroll($choseArea) {

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

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

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