Blogger Information
Blog 44
fans 0
comment 0
visits 35565
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
JS中拖拽元素实现的原理-2019年1月18日
的博客
Original
697 people have browsed it

实例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>拖拽</title>
    <style>
        #ball {
            width: 50px;
            height: 50px;
            background-color: lightpink;
            border-radius: 50%;
            box-shadow: 2px 2px 1px #888;
            position:absolute;
        }
    </style>
</head>
<body>
    <div id="ball"></div>

    <script>
    // onmousedown: 选择, onmouseover: 移动, onmouseup:放下

    var ball = document.getElementById('ball');

    // 选中这个小球
    // onmousedown
    //找到小球的位置: 
        // 当前鼠标到小球边沿的距离相对是不变的,变得只是小球到左边与顶部的距离
        // 这个不变的距离 ,是鼠标点击下去的一瞬间就确定了,就可以求出来了
            // 根据当前鼠标到当前可视区的距离

        // 求出鼠标当前位置
    ball.onmousedown = function (event) {
        var x = event.clientX - this.offsetLeft;
        var y = event.clientY - this.offsetTop;
        console.log(x, y);  // offsetLeft只读,返回数值

        // 移太快,鼠标跑出小球了,怎么办, 应该把事件添加到整个文档就可以了,再快, 也不会跑出浏览器窗口吧
        // ball.onmousemove = function (event) {
        document.onmousemove = function (event) {
            ball.style.left = event.clientX - x + 'px';
            console.log(ball.style.left);  // 注意返回的是字符串
            ball.style.top = event.clientY - y + 'px';
        }

        // ball.onmouseup = function () {
        document.onmouseup = function () {
            // ball.onmousemove = null;
            document.onmousemove = null; 
        }
    }
    </script>
</body>
</html>

运行实例 »

点击 "运行实例" 按钮查看在线实例

Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post