[jquery实现手机验证码]jquery实现手机网站div层滑动的例子

更新时间:2019-11-20    来源:jquery    手机版     字体:

【www.bbyears.com--jquery】

body很长,可以滑动,body头部有一个模拟下拉的选择框。下拉选择有滚动轴,如下图。

 

enter image description here

 

我给body一个overflow:hidden和高度是没有用的。手机网站上背景还是可以滑动,然后我给body一个touchmove的preventdefault()阻止事件,body滑动组织了,PC上面是可以了,但是手机上面滑动div还是会导致底部body的滑动,我给div 一个阻止冒泡的事件stopPropagation(),手机网站上面还是不可以。


关于preventdefault和stopPropagation,后面有时间会讲解其区别。

解决方案

我经过反复测试,返现滚动轴滚到底部的时候,会触发body的滑动,那么我就在事件滚到底部的时候对表层的div做一个touchmove的阻止。到达滚动轴底部,向下滑动,阻止事件,向上滑动,开启事件。为此就要判断touchmove的方向了。

$("body").on("touchstart", function(e) {
    e.preventDefault();
    startX = e.originalEvent.changedTouches[0].pageX,
    startY = e.originalEvent.changedTouches[0].pageY;
});
$("body").on("touchmove", function(e) {
    e.preventDefault();
    moveEndX = e.originalEvent.changedTouches[0].pageX,
    moveEndY = e.originalEvent.changedTouches[0].pageY,
    X = moveEndX - startX,
    Y = moveEndY - startY;

    if ( Math.abs(X) > Math.abs(Y) && X > 0 ) {
        alert("left 2 right");
    }
    else if ( Math.abs(X) > Math.abs(Y) && X < 0 ) {
        alert("right 2 left");
    }
    else if ( Math.abs(Y) > Math.abs(X) && Y > 0) {
        alert("top 2 bottom");
    }
    else if ( Math.abs(Y) > Math.abs(X) && Y < 0 ) {
        alert("bottom 2 top");
    }
    else{
        alert("just touch");
    }
});

上面的方法是判断touchmove的滑动方向。

      $("#haorooms底层背景").bind("touchmove", function (e) {
            e.preventDefault();
        });
        $(".滚动的父亲").bind("touchstart", function (events) {
            startY = events.originalEvent.changedTouches[0].pageY;
        });
        $(".滚动的父亲 ul").bind("touchmove", function (e) {
            var ulheight = $(this).height();
            var scrollTop = $(this).scrollTop();
            var scrollheight = $(this)[0].scrollHeight;
            if (ulheight + scrollTop + 20 >= scrollheight) { //滚到底部20px左右
                $(".滚动的父亲").bind("touchmove", function (event) {
                    moveEndY = event.originalEvent.changedTouches[0].pageY,
                            theY = moveEndY - startY;
                    if (theY > 0) { //用上面的abs()更加准确!
                        $(".滚动的父亲").unbind("touchmove");
                    }
                    if (theY < 0) {
                        event.preventDefault();
                    }
                })
            }
            if (scrollTop < 20) {//滚到顶部20px左右
                $(".滚动的父亲").bind("touchmove", function (event) {
                    moveEndY = event.originalEvent.changedTouches[0].pageY,
                            theY = moveEndY - startY;
                    if (theY > 0) {
                        event.preventDefault();
                    }
                    if (theY < 0) {
                        $(".滚动的父亲").unbind("touchmove");
                    }
                })
            }
        });

本文来源:http://www.bbyears.com/wangyezhizuo/80261.html