Moving end suspension ball

Posted by iRock on Sun, 03 May 2020 13:39:32 +0200

This is a common case when writing mobile terminal. Many web apps will have a mobile phone like suspension ball, which can be dragged on the interface at will, and then clicking on it is a connection. The effect chart is as follows

In the figure, there is a customer service suspension ball that is connected by a window and can slide freely. The code is as follows

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .div{
            width: 100px;
            height: 50px;
            position:fixed;
            background-color: red;
            border-radius:25px;
        }
    </style>
</head>
<body>
<div class="div" id="div"></div>
</body>
<script>
    window.onload=function(){
        var flag = 0; //Mark drag or click
        var oDiv = document.getElementById('div');
        var disX,moveX,L,T,starX,starY,starXEnd,starYEnd;
        oDiv.addEventListener('touchstart',function(e){
            flag = 0;
            e.preventDefault();//Prevent page scrolling and zooming when touching
            disX = e.touches[0].clientX - this.offsetLeft;
            disY = e.touches[0].clientY - this.offsetTop;
//Coordinates when fingers are pressed
            starX = e.touches[0].clientX;
            starY = e.touches[0].clientY;
//console.log(disX);
        });
        oDiv.addEventListener('touchmove',function(e){
            flag = 1;
            L = e.touches[0].clientX - disX ;
            T = e.touches[0].clientY - disY ;
//The difference between the current position and the starting position when moving
            starXEnd = e.touches[0].clientX - starX;
            starYEnd = e.touches[0].clientY - starY;
//console.log(L);
            if(L<0){//Limit the X range of drag, not drag out of the screen
                L = 0;
            }else if(L > document.documentElement.clientWidth - this.offsetWidth){
                L=document.documentElement.clientWidth - this.offsetWidth;
            }
            if(T<0){//Limit the Y range of dragging, cannot drag out the screen
                T=0;
            }else if(T>document.documentElement.clientHeight - this.offsetHeight){
                T = document.documentElement.clientHeight - this.offsetHeight;
            }
            moveX = L + 'px';
            moveY = T + 'px';
//console.log(moveX);
            this.style.left = moveX;
            this.style.top = moveY;
        });
        window.addEventListener('touchend',function(e){
//alert(parseInt(moveX))
//Judge sliding direction
            if(flag === 0) {//click
                window.location.href='http://www.baidu.com';
                    }
        });
    }
</script>
</html>

The code can be directly referenced, easy to understand, and only applicable to the mobile end.

Topics: Mobile