方块拖拽(原生js)

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>方块拖拽</title>
		<style type="text/css">
			#box {
				width: 100px;
				height: 100px;
				background-color: #FF7F50;
				position: absolute;
				text-align: center;
			}

			#box2 {
				width: 100px;
				height: 100px;
				background-color: yellow;
				position: absolute;
				left: 200px;
				top: 200px;
				position: absolute;
			}
		</style>
		<script>
			/**
			 * 拖拽流程:
			 * 		1、当鼠标在被拖拽元素上按下时,开始摇拽    onmousedown
			 * 		2、当鼠标移动时被拖拽元素跟随元素鼠标移动  onmousemove
			 * 		3、当鼠标松开时,被拖拽元素固定在当前位置  onmouseup
			 */
			window.onload = function() {
				var box = document.getElementById("box");
				var box2 = document.getElementById("box2");

				drag(box);
				drag(box2);
			}

			function drag(obj) {
				obj.onmousedown = function(event) {
					/**
					 * 针对(**)IE8不支持解决方法
					 * 	setCapture()
					 * 	  - 该方法只支持IE,但是在火狐中调用时不会报错
					 * 		chrome中会报错
					 */

					box.setCapture && box.setCapture();

					event = event || window.event;
					var le = event.clientX - obj.offsetLeft;
					var to = event.clientY - obj.offsetTop;

					document.onmousemove = function(event) {
						event = event || window.event;

						var left = event.clientX - le;
						var top = event.clientY - to;

						obj.style.left = left + "px";
						obj.style.top = top + "px";
					};

					document.onmouseup = function() {
						//取消document的onmousemove事件
						document.onmousemove = null;
						//取消document的onmouseup事件
						document.onmouseup = null;
						obj.releaseCapture && obj.releaseCapture();
						
					};

					/**
					 * 拖拽网页中内容,尤其是文字或图片,浏览器会自动搜索,此时会有拖拽功能异常
					 * 这是浏览器自动行为,若不需要,需要取消(**)
					 * IE8不支持
					 */

					return false;
				};
			}
		</script>
	</head>
	<body>
		<div id="box">可拖拽</div>
		<div id="box2"></div>
	</body>
</html>

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值