js拖拽

2020-10-28 10:29:09 浏览数 (1)

代码语言:javascript复制
<!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>

思路;举个例子把,好把。我刚开始是

0 人点赞