阅读 517

js 如何实现拖动滑块

js 如何实现拖动滑块

实现拖动滑块,先分析,滑块可以拖动应该改变滑块在页面中的坐标,那就采用定位拿到元素的 top 和 left 对它们进行赋值,接下来就是准备事件,既然是鼠标拖动应该具备 mousedownmousemovemouseup 三种事件,通过 mousedown 鼠标按下事件选中滑块,mousemove 事件拖动滑块,在拖动滑块的时候获取鼠标在可视窗口的坐标赋值给滑块的 top 和 left

具体代码实现

<!DOCTYPE html>
<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>
复制代码

运行

在这里插入图片描述

文章分类
前端
文章标签