鼠标拖拽

  •  拖拽元素记得先开启元素的定位(绝对定位,相对定位)
  • 大量的重复性的Demo设置为函数的形式
  • 判断是否有函数等兼容性问题的时候可以使用  ||  && 的方式来简便的解决问题
  • 主要浏览器差异带来的区别
  • 在计算偏移量时候使用鼠标的偏移量减去元素的偏移量
  • 事件
<!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(){
				var box1 = document.getElementById("box1");
				var box2 = document.getElementById("box2");
				
				drag(box1);
			 	//提取函数、、
			};
				
				function drag(obj){
				obj.onmousedown = function(event){
					
					//设置box1 捕获所有的鼠标按下事件
					//如果有则执行,没有则不执行跳过
					
					obj.setCapture && obj.setCapture();
					
					event = event || window.event;
					
					//div的偏移量  鼠标.clentx - 元素.offsetLeft
					var ol = event.clientX - obj.offsetLeft;
					var ot = event.clientY - obj.offsetTop;
					document.onmousemove = function(event){
						
						var left = event.clientX - ol;
						var top = event.clientY - ot;
						
						
						obj.style.left = left+"px";
						obj.style.top = top+"px";
				};
				document.onmouseup = function(event){
					
					//取消documentonmousemove事件
					document.onmousemove = null;
					document.onmouseup = null;
					
					//当鼠标松开时,取消对事件的捕获
					obj.releaseCapture && obj.releaseCapture();
				};
				//当拖拽网页中的内容时,此时会导致异常。
				//默浏览器的默认的行为,可用通过return false来设置   ie8 不适用
				
				return false;			 	
			 };
			
			}
			
		</script>
	</head>
	<body>
		<div id="box1"></div>
		
		<div id="box2"></div>

	</body>
</html>
发布了183 篇原创文章 · 获赞 19 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_43641432/article/details/103358182