30、JavaScript中简单拖拽DIV的实现

1、DIV拖拽的实现
     1.1 简易拖拽
             .拖拽原理
                --距离不变
                --三个事件
                   onmousedown  存储距离,并发生onmousemove
                   onmousemove  根据距离,计算div最新的位置
                   onmouseup    停止拖拽的发生,也就是当onmouseup时,onmousemove取消掉
                 --事件之间的关系
                   1. 鼠标的onmousedown没按下之前,鼠标的onmousemove移动事件不会发生

                       1.1 修改为,在onmousedown的时候,再添加onmousemove事件


2、代码

     2.1 css代码

               <style type="text/css">
			* {
				padding: 0px;
				margin: 0px;
			}
			
			#myDiv {
				width: 100px;
				height: 100px;
				background: red;
				position: absolute;
			}
		</style>

      2.2 JavaScript代码

             <script type="text/javascript">
			window.onload = function() {
				var oDiv = document.getElementById("myDiv");
				//保存鼠标位置disX,距离DIV左边边框的距离,就是,event.clientX - oDiv.offsetLeft;
				var disX = 0;
				//保存鼠标位置disY,距离DIV上边边框的距离,就是,event.clientY - oDiv.offsetTop;
				var disY = 0;
				/*1、当鼠标按下的时候,保存下当前DIV的top和left的数值*/
				oDiv.onmousedown = function(ev) {
					var oEvent = ev || event;
					disX = oEvent.clientX - oDiv.offsetLeft;
					disY = oEvent.clientY - oDiv.offsetTop;
					oDiv.style.cursor = "pointer";
					/*2、当鼠标移动的时候,计算DIV新的位置*/
					document.onmousemove = function(ev) {
							var oEvent = ev || event;
							var left = oEvent.clientX - disX;
							var top = oEvent.clientY - disY;
							/*可是区域的宽度大小*/
							var clientWidth = document.documentElement.clientWidth;
							var clientHeight = document.documentElement.clientHeight;
							/*4、进行边界的判断*/
							/*检测左边的边界*/
							if (left < 0) {
								left = 0;
							}
							/*检测右边的边界*/
							else if (left > clientWidth - oDiv.offsetWidth) {
								left = clientWidth - oDiv.offsetWidth;
							}
							/*上边界的检测*/
							if (top < 0) {
								top = 0;
							}
							/*下边界的检测*/
							else if (top > clientHeight - oDiv.offsetHeight) {
								top = clientHeight - oDiv.offsetHeight;
							}
							oDiv.style.left = left + "px";
							oDiv.style.top = top + "px";
						}
						//3、当鼠标抬起来的时候,让onmousemove取消
					document.onmouseup = function() {
						//3.1 取消onmousemove事件
						oDiv.style.cursor = "default";
						document.onmousemove = null;
						document.onmouseup = null;
					}
				}
			};
		</script>

      2.3 html代码

        <body>
		<div id="myDiv">
		</div>
	</body>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值