118-119-----JS基础-----拖拽(一与二)

一 代码

有点东西,用到的时候再详细测一下即可。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			
			#box1{
      
      
				width: 100px;
				height: 100px;
				background-color: red;
				position: absolute;
			}
			
			#box2{
      
      
				width: 100px;
				height: 100px;
				background-color: yellow;
				position: absolute;
				
				left: 200px;
				top: 200px;
			}
			
		</style>
		
		<script type="text/javascript">
			
			window.onload = function(){
      
      
				/*
				 * 1. 拖拽box1元素
				 *  - 拖拽的流程
				 * 		1.当鼠标在被拖拽元素上按下时,开始拖拽      onmousedown
				 * 		2.当鼠标移动时被拖拽元素跟随鼠标移动        onmousemove
				 * 		3.当鼠标松开时,被拖拽元素固定在当前位置	onmouseup
				 */
				
				//获取box1
				var box1 = document.getElementById("box1");
				// 2. 为box1绑定一个鼠标按下事件
				//当鼠标在被拖拽元素上按下时,开始拖拽  onmousedown
				box1.onmousedown = function(event){
      
      
					event = event || window.event;
					//div元素要调整的水平偏移量 鼠标.clentX - 元素.offsetLeft
					//div元素要调整的垂直偏移量 鼠标.clentY - 元素.offsetTop
                    //这样调整后,就可以使用户按下鼠标后,鼠标可以在元素的对应位置,而不是鼠标一直处于元素的左上角
					var ol = event.clientX - box1.offsetLeft;
					var ot = event.clientY - box1.offsetTop;
					
					
					// 3. 为document绑定一个onmousemove事件
					document.onmousemove = function(event){
      
      
						event = event || window.event;
						//当鼠标移动时被拖拽元素跟随鼠标移动 onmousemove
						//获取 鼠标的坐标减去上面元素要调整的距离后,设置修改元素的style位置即可。
						var left = event.clientX - ol;
						var top = event.clientY - ot;
						//修改box1的位置
						box1.style.left = left+"px";
						box1.style.top = top+"px";
						
					};
					
					// 4. 为document绑定一个鼠标松开事件
					document.onmouseup = function(){
      
      
						//当鼠标松开时,被拖拽元素固定在当前位置	onmouseup
						//取消document的onmousemove事件
						document.onmousemove = null;
						//取消document的onmouseup它自己的事件,防止再次点击还会被触发。
						document.onmouseup = null;
					};
				};
				
				
			};
			
			
		</script>
	</head>
	<body>
		<div id="box1"></div>
		
		<div id="box2"></div>
	</body>
</html>

おすすめ

転載: blog.csdn.net/weixin_44517656/article/details/121494652