Blame view

public/js/plugin/inner-scroll.js 2.46 KB
张丽霞 authored
1 2 3 4 5 6 7
/**
 * 弹出层可以滚动,遮盖层禁止滚动插件
 *
 * @author liangzhifeng<zhifeng.liang@yoho.cn>
 * @date: 2016/02/22
 */
陈峰 authored
8
let $ = require('yoho-jquery');
张丽霞 authored
9 10 11 12 13 14 15 16 17 18 19 20 21 22

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) {
陈峰 authored
23
    let delta = e.wheelDelta || e.originalEvent.wheelDelta || e.detail || 0,
张丽霞 authored
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
        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;
        }
    }
}
陈峰 authored
45 46 47 48 49 50 51 52 53
function enableScroll($choseArea) {

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

    $(document).off('mousewheel', preventDefault);
    $(document).off('touchmove', preventDefault);
}
张丽霞 authored
54
function disableScroll($choseArea) {
陈峰 authored
55
    enableScroll($choseArea);
陈峰 authored
56
    let startX, startY;
张丽霞 authored
57 58 59 60 61 62 63 64 65 66 67 68

    // 内部可滚
    $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) {
陈峰 authored
69
        let deltaX = e.originalEvent.changedTouches[0].pageX - startX,
张丽霞 authored
70 71
            deltaY = e.originalEvent.changedTouches[0].pageY - startY;
陈峰 authored
72
        let box = $(this).get(0);
张丽霞 authored
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104

        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;