Front-end——jQuery实现一个div随意拖动

步骤:

  1. 点击时刻记录原来 距左和距顶的距离
  2. 记录鼠标按下时刻的x坐标 和 y坐标
  3. 添加鼠标移动事件
  4. 在鼠标移动事件中,再获取 移动后 x坐标和y坐标
  5. 最终元素距顶的距离 = 移动后的Y坐标 - 移动前Y坐标 + 原本距顶的距离
  6. 最终元素距左的距离 = 移动后的X坐标 - 移动前X坐标 + 原本距左的距离
<!!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<script src="js/jquery.min.js"></script>
		<style>
			*{
				margin: 0;
				padding: 0;
			}
			#app{
				height: 200px;
				width: 200px;
				border: 2px solid #000000;
				position: absolute;
				top: 20px;
				left : 30px
			}
		</style>
	</head>
	
	<body>
		<div id="app"></div>
		<script>
			// $(function(){}) 用于加载页面
			$(function(){
				$("#app").mousedown(function(a){
				   //获取app元素 距左和距顶的距离
				   const startLeft = $("#app").offset().left
				   const startTop =  $("#app").offset().top
				   
				   //记录鼠标按下时刻的x坐标和y坐标
				   const startX = a.pageX
				   const startY = a.pageY
				   
				   $(document).mousemove(function(b){
					   //记录鼠标移动后的x坐标和y坐标
					   const endX = b.pageX
					   const endY = b.pageY
					   
					   //计算最终的距顶和距左的距离
					   const top = endY - startY + startTop
					   const left = endX - startX + startLeft
					   
					   //为app设置 left和top样式
					   $("#app").css({
						   top: top + 'px',
						   left:left+ 'px'
					   })
				   })
				})
			})
		</script>
	</body>
</html>

以上实现的鼠标放开后,div也是跟随着移动,现在需要实现鼠标抬起事件,加入一个锁(flag),按照flag的状态判断是否移动div

<!!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<script src="js/jquery.min.js"></script>
		<style>
			*{
				margin: 0;
				padding: 0;
			}
			#app{
				height: 200px;
				width: 200px;
				border: 2px solid #000000;
				position: absolute;
				top: 20px;
				left : 30px
			}
		</style>
	</head>
	
	<body>
		<div id="app"></div>
		<script>
			// $(function(){}) 用于加载页面
			$(function(){
				$("#app").mousedown(function(a){
				   //获取app元素 距左和距顶的距离
				   const startLeft = $("#app").offset().left
				   const startTop =  $("#app").offset().top
				   
				   //记录鼠标按下时刻的x坐标和y坐标
				   const startX = a.pageX
				   const startY = a.pageY
				   
				   let flag = true
				   
				   $(document).mousemove(function(b){
					   if(flag){
						   //记录鼠标移动后的x坐标和y坐标
						   const endX = b.pageX
					       const endY = b.pageY
					   
					       //计算最终的距顶和距左的距离
					       const top = endY - startY + startTop
					       const left = endX - startX + startLeft
					   
					       //为app设置 left和top样式
					       $("#app").css({
						      top: top + 'px',
						      left:left+ 'px'
					       })
					  }
					  $(document).mouseup(function(){
					   	 flag = false
					  })
				   })
				})
			})
		</script>
	</body>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_42067873/article/details/112462525