如何在webapp里面做一个类似于iphone屏幕上的小白点,可以随意推动,又不会遮挡下方操作

如何在webapp里面做一个类似于iphone屏幕上的小白点,可以随意推动,又不会遮挡下方操作

已邀请:

juanpingzhao

赞同来自:

<style>
    .dot{
        position: fixed;
        left: 20px;
        top: 20px;
        width:20px;
        height:20px;
        background:rgba(255,255,255,.5);
    }
</style>

<body>
    <div class="dot"></div>
</body>

<script>
    var ww = $(window).width(), wh = $(window).height();
    var x , y;
    var hastouch = "ontouchstart" in window ? true : false,
                tapstart = hastouch ? "touchstart" : "mousedown",
                tapmove = hastouch ? "touchmove" : "mousemove",
                tapend = hastouch ? "touchend" : "mouseup";
     $(".dot")[0].addEventListener(tapstart, function (e) {
            x = e.targetTouches[0].pageX;
            y = e.targetTouches[0].pageY;

            var pos = $(".dot").position();

            $(".dot").css({
                left: pos.left,
                top: pos.top
            })
        });

        $(".dot")[0].addEventListener(tapmove, function (e) {
            e.stopPropagation();
            var pos = $(".dot").position();
            pos.left = pos.left + e.targetTouches[0].pageX - x;
            pos.top = pos.top + e.targetTouches[0].pageY - y;

            if (pos.left < 0) {
                pos.left = 0;
            }

            if (pos.left + 60 > ww) {
                pos.left = ww - 60;
            }

            if (pos.top <= 0) {
                pos.top = 0;
            }

            if (pos.top + 60 > wh) {
                pos.top = wh - 60;
            }

            $(".dot").css({
                left: pos.left,
                top: pos.top
            });
            x = e.targetTouches[0].pageX;
            y = e.targetTouches[0].pageY;

            e.preventDefault();
        });     
</script>

eric1386

赞同来自:

做一个绝对定位的div 然后添加拖动事件

要回复问题请先登录注册