js-元素拖拽属性案例

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			* {
				margin: 0;
				padding: 0;
			}

			img {
				position: absolute;
				width: 300px;
				height: 200px;
				background-color: red;
			}

			body {
				height: 3000px;
			}
		</style>
		<script type="text/javascript">
			window.onload = function() {
				//需求:鼠标按在div上 并移动, div就跟随鼠标移动
				var div = document.getElementsByTagName('img')[0];
				//1 按住鼠标
				div.onmousedown = function(e) {
					var ev = window.event || e;
					//相对于html文档
					// console.log(ev.pageX,ev.pageY)
					//相对于屏幕
					// console.log(ev.clientX,ev.clientY)
					//兼容处理	没有滚动条可以不用
					var sT = document.documentElement.scrollTop || document.body.scrollTop;
					var sL = document.documentElement.scrollLeft || document.body.scrollLeft;
					//计算鼠标位置	差
					var a = ev.clientY + sT - this.offsetTop;
					var b = ev.clientX + sL - this.offsetLeft;
					//ie6- 使用全局捕获解决拖拽问题
					if (this.setCapture) {
						this.setCapture();
					}
					//3 拖动
					document.onmousemove = function(e) {
						var ev = window.event || e;
						//获取鼠标位置
						var sT = document.documentElement.scrollTop || document.body.scrollTop;
						var sL = document.documentElement.scrollLeft || document.body.scrollLeft;
						var x = ev.clientX + sL;
						var y = ev.clientY + sT;
						var dx = x - b;
						var dy = y - a;
						//限制移动区域
						//上
						if (dy <= 0) {
							dy = 0;
						}
						//左
						if (dx <= 0) {
							dx = 0;
						}
						//右
						if (dx >= document.documentElement.clientWidth + sL - div.clientWidth) {
							dx = document.documentElement.clientWidth + sL - div.clientWidth;
						}
						//下
						if (dy >= document.documentElement.clientHeight + sT - div.clientHeight) {
							dy = document.documentElement.clientHeight + sT - div.clientHeight
						}

						//设置位置
						div.style.left = dx + 'px';
						div.style.top = dy + 'px';
						return false; //防止拖拽图片和文字的时候出现的bug
					}
				}
				//抬起鼠标
				div.onmouseup = function() {
					//取消事件
					document.onmousemove = null;
					if (this.releaseCapture) {
						this.releaseCapture(); //释放捕获
					}
				}

			}
		</script>
	</head>
	<body>
		<img src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1586348889091&di=7f1c3c853bcaee2ef9bdd98e87d19be6&imgtype=0&src=http%3A%2F%2Fcdn.wecarepet.net%2Fupload%2Fimage_26_1458374949521.jpeg">
	</body>
</html>

 

posted @ 2023-01-04 21:04  JackieDYH  阅读(5)  评论(0编辑  收藏  举报  来源