当我移动美女图片的时候,鼠标抬起来,但是图片会继续移动,应该怎样修改呢?
发布于 6 年前 作者 leigang 11871 次浏览 来自 问答

当我移动美女图片的时候,鼠标抬起来,但是图片会继续移动,应该怎样修改呢?

<!DOCTYPE html>
<html>
<head>
	<title>拖拽</title>
	<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=yes"/>
	<script type="text/javascript">
		window.onload=function(){
			var box1=document.getElementById("div1");
			var box2=document.getElementById("div2");

			var img1=document.getElementById("img1")

			drag(box1)
			drag(box2)
			drag(img1)

			function drag(obj){
				obj.onmousedown=function(event){
					var offsetX=event.offsetX;
					var offsetY=event.offsetY;

					document.onmousemove=function(event){
						var event=event||window.event;
						obj.style.left=(event.clientX-offsetX)+"px";
						obj.style.top=(event.clientY-offsetY)+"px";

					}

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

	<style type="text/css">
		div{
			width: 100px;
			height: 100px;
			border:1px solid #000;
			color: white;
			display: flex;
			justify-content: center;
			align-items: center;
			position: absolute;
		}
		#div1{
			background: red;
			/*left: 100*/
		}
		#div2{
			background: orange;
			left: 200px;
			top: 200px;

		}
	</style>
</head>
<body>
	<div id="div1">div1</div>
	<div id="div2">div2</div>
	<img src="./images/meinv.jpg" id="img1" style="position: absolute;width: 100px;height: 100px">
</body>
</html>
回到顶部