<!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)
????????????????//?清除事件?-?必須清除的是命名函數(shù)赏殃!
????????????????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>