How does JS implement drag slider

To achieve drag slider, first analysis, the slider can drag should change the coordinates of the slider in the page, then use positioning to get the top and left elements to assign values to them, the next is to prepare events, since it is a mouse drag should have mousedown, Mousemove, mouseup three kinds of events, Select the slider by mouseDown, and drag the slider by Mousemove. When dragging the slider, get the coordinates of the mouse in the visual window assigned to the top and left of the slider

Concrete code implementation

<! DOCTYPEhtml>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        div {
            width: 60px;
            height: 60px;
            background-color: coral;
            border-radius: 20%;
            position: absolute;
            border: 6px solid skyblue;
            left: 0;
            top: 0;
        }
    </style>
</head>

<body>
    <div></div>
    <script>
        let div = document.querySelector('div')
        let x, y
        let fn = function (e) {
            // console.log('hhhhhhhh')
            div.style.left = e.clientX - x + 'px'
            div.style.top = e.clientY - y + 'px'
            if (e.clientX - x < 30) {
                div.style.left = 0
            }
            if (e.clientY - y < 30) {
                div.style.top = 0
            }
            if (e.clientX - x > document.documentElement.clientWidth - div.offsetWidth - 30) {
                div.style.left = document.documentElement.clientWidth - div.offsetWidth + 'px'
            }
            if (e.clientY - y > document.documentElement.clientHeight - div.offsetHeight - 30) {
                div.style.top = document.documentElement.clientHeight - div.offsetHeight + 'px'
            }
        }
        div.addEventListener('mousedown'.function (e) {
            x = e.offsetX
            y = e.offsetY
            document.addEventListener('mousemove', fn)
        })
        div.addEventListener('mouseup'.function () {
            document.removeEventListener('mousemove', fn)
        })
    </script>
</body>

</html>
Copy the code

run