問題背景:
在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');//設置父級可以滾動