首页 > 技术文章 > ionic 禁止页面在微信中上下滑动

ywang 2017-01-22 16:32 原文

问题背景:

在ionic项目中需要做一个拖拽替换的效果。放到微信中,在拖拽元素的时候,页面也会跟着上下滑动,导致效果非常不好,所以需要禁止页面上下滑动。

需要实现的效果:

当不拖拽元素的时候,元素的父级可以上下滑动。当拖拽元素的时候,禁止页面及父级上下滑动

上代码:

var overScroll = function(el,isScroll) {//判断isScroll是否允许el上下滑动
    el.addEventListener('touchstart', function() {
        var top = el.scrollTop
            , totalScroll = el.scrollHeight
            , currentScroll = top + el.offsetHeight;
        //If we're at the top or the bottom of the containers
        //scroll, push up or down one pixel.
        //
        //this prevents the scroll from "passing through" to
        //the body.
        if(top === 0) {
            el.scrollTop = 1;
        } else if(currentScroll === totalScroll) {
            el.scrollTop = top - 1;
        }
    });
    el.addEventListener('touchmove', function(evt) {
        //if the content is actually scrollable, i.e. the content is long enough
        //that scrolling can occur
            if(el.offsetHeight < el.scrollHeight){
                if(isScroll == 'no'){
                    evt._isScroller = false;
                }else{
                    evt._isScroller = true;
                }
            }
    });
}            

当页面加载的时候:

    overScroll(document.querySelector('#shortcutItems'),'yes');//允许父级元素上下滑动
    document.body.addEventListener('touchmove', function(evt) {//禁止页面元素上下滑动
        //In this case, the default behavior is scrolling the body, which
        //would result in an overflow.  Since we don't want that, we preventDefault.
        if(!evt._isScroller) {
            evt.preventDefault();
        }
    });

接下来元素拖拽自然有touchstart、touchmove和touchend事件

在touchstart事件中添加:

overScroll(document.querySelector('#shortcutItems'),'no');//设置父级不能滚动

在touchend事件中添加:

overScroll(document.querySelector('#shortcutItems'),'yes');//设置父级可以滚动

 

推荐阅读