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">
    <meta charset="UTF-8">
            width: 100px;
            height: 50px;
            background-color: red;
<div class="div" id="div"></div>
        var flag = 0; //Mark drag or click
        var oDiv = document.getElementById('div');
        var disX,moveX,L,T,starX,starY,starXEnd,starYEnd;
            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;
            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;
            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
            }else if(T>document.documentElement.clientHeight - this.offsetHeight){
                T = document.documentElement.clientHeight - this.offsetHeight;
            moveX = L + 'px';
            moveY = T + 'px';
   = moveX;
   = moveY;
//Judge sliding direction
            if(flag === 0) {//click

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

Topics: Mobile