鼠标拖拽事件,拖拽照片等

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<style type="text/css">
		#box1{
			width:100px;
			height: 100px;
			background-color: gray;
			position: absolute;
			
		}
		#box2{
			width:100px;
			height: 100px;
			left:200px;
			background-color: green;
			position: absolute;
			
		}
	</style>
	<script type="text/javascript">
		window.onload=function(){
			/*
			 * 拖拽box1元素
			 * -拖拽流程
			 * 	1.鼠标按下,开始拖 onmousedown
			 * 	2.鼠标移动,跟随移动onmousemove
			 * 	3.当鼠标松开,被拖拽元素固定在当前位置onmouseup
			 */
			 var box1=document.getElementById("box1")
			 box1.onmousedown=function(){
			 	document.onmousemove=function(event){
			 		event=event||window.event
			 		var x=event.clientX;
			 		var y=event.clientY;
			 		//box1的位置
			 		box1.style.left=event.clientX+"px"
			 		box1.style.top=event.clientY+"px"
			 		console.log(box1.style.left)
			 		
			 	}
			 }
			 document.onmouseup=function(){
			 	//当鼠标松开,元素固定在当前位置
			 	//取消document。onmousemove=null
			 	/*
			 	 * 兄弟元素会出现问题,当在鼠标兄弟元素时,触发兄第元素的mouseup
			 	 * 因此这里松手按钮要给整个页面,这样子无论在哪里松手都会停,但
			 	 * 如果完全重合就无法在脱出
			 	 */
			 	document.onmousemove=null;
			 	document.onmouseup=null;
			 }
		}
	</script>
	<body>
		<div id="box1"></div>
		<div id="box2"></div>
	</body>
</html>

    原文作者:JOJO-狗蛋
    原文地址: https://blog.csdn.net/weixin_44828588/article/details/113966477
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞