0
点赞
收藏
分享

微信扫一扫

JavaScript 拖拽div

村里搬砖的月野兔 2022-05-03 阅读 73
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>拖拽div</title>
	<style type="text/css">
		#box1{
			width: 60px;
			height: 60px;
			background-color: green;
			position: absolute;
		}
		#box2{
			width: 1890px;
			height: 860px;
			background-color: pink;
		}
	</style>
	<script type="text/javascript">
		window.onload=function(){
			var box1=document.getElementById("box1");
			//1.鼠标按下,onmousedown
			box1.onmousedown=function(event){
				//div的偏移量:鼠标.clientX-元素.offsetLeft
				//div的偏移量:鼠标.clientY-元素.offsetTop
				var ol=event.clientX-box1.offsetLeft;
				var ot=event.clientY-box1.offsetTop;
				event=event||window.event;
				//2.拖拽,onmousemove
				document.onmousemove=function(event){
					event=event||window.event;
					var left=event.clientX-ol;
					var top=event.clientY-ot;
					box1.style.left=left+"px";
					box1.style.top=top+"px";
				};
				//3.鼠标松开,onmouseup
				document.onmouseup=function(){
					document.onmousemove=null;
					document.onmouseup=null;
				};
				return false;//取消浏览器默认行为,IE8及以下版本不兼容
			};
		}
	</script>
</head>
<body>
	<div id="box1"></div>
	<div id="box2"></div>
</body>
</html>

(作者观看的学习视频:B站尚硅谷)

 

举报

相关推荐

0 条评论