js拖拽

2020-10-02 12:00:45
<!doctype html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <title></title> 
    <style type="text/css">
*{margin:0;padding: 0;;list-style: none;}
#div{width: 100px;height: 100px;background: black;position: absolute;}

    </style>
</head>
<body>
asdjalksda
<div id='div'></div>

<script type="text/javascript">
	
div.onmousedown = function(e){
	var ev = e || event;
	var l = ev.clientX - div.offsetLeft;//獲取到div到div的滑鼠之間的距離.
	var t = ev.clientY - div.offsetTop;



	document.onmousemove = function(e){
		var ev = e || event;
		div.style.left = ev.clientX - l+ 'px';//移動後的滑鼠(350 350)減去down時候的div到div的滑鼠之間(150-100=50)的距離.等於左上角在哪裡。
		//比如down左上角是100 100,滑鼠是150 150,移動後是左上角是300 滑鼠是350的話,
		//350-50=300就行了啊,左上角是300 300啊。滑鼠在div裡·,就是300+50=350啊。
		div.style.top = ev.clientY - t + 'px';

	};

	document.onmouseup = function(){
		document.onmousemove = null;//擡起清空.
		document.onmouseup = null;

	};
	return false;
};

</script>
</body>
</html>

思路;舉個例子把,好把。我剛開始是