案例:鼠标拖拽

 

<!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>Document</title>

    <style>

        div{

            width: 100px;

            height: 100px;

            background: red;

            position: absolute;

        }

    </style>

</head>

<body>

    <div></div>

    <script src="mTween.js"></script>

    <script>

        // 鼠标按下 mousedown

        // 鼠标移动 mousemove 不断的改变元素的top/left

        // 鼠标抬起 mouseup 

        var div=document.querySelector('div');

        // 1. 鼠标点击的位置

        var startPos={}

        // 2. 元素的初始位置

        var boxPos={}

        div.addEventListener('mousedown',function(e){

            startPos.x=e.clientX;

            startPos.y=e.clientY;

            boxPos.x=css(div,'left')

            boxPos.y=css(div,'top')

            // 鼠标移动过程中改变元素的位置

            document.addEventListener('mousemove',drag)

             // 清除鼠标移动事件

            document.addEventListener('mouseup',function(){

                console.log(1)

                // 清除事件 - 必须清除的是命名函数!

                document.removeEventListener('mousemove',drag)

            },{

                // 只绑定一次事件

                once:true

            })

        })

        function drag(e){

            // console.log('move')

            // 当前位置

            var nowPos={

                x:e.clientX,

                y:e.clientY

            }

            // 当前鼠标位置 - 初始鼠标位置 = 移动距离

            var dis={

                x:nowPos.x-startPos.x,

                y:nowPos.y-startPos.y

            }

            // 移动距离+元素的初始位置 = 元素最新的位置

            var newPos={

                l:dis.x+boxPos.x,

                t:dis.y+boxPos.y

            }

 

            // 修改样式

            css(div,'top',newPos.t)

            css(div,'left',newPos.l)

        }

    </script>

</body>

</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值