js 控制div 横向 纵向 移动

  //div 拖动 div的ID
		
             var container = document.getElementById("DivName")
               container.onmousedown = function() {
			//获取鼠标当前坐标 
			var pageX = event.clientX;
			var pageY = event.clientY;
			//获取block的坐标,左边界和上边界 
			var offX = parseInt(this.style.left) || 0;
			var offY = parseInt(this.style.top) || 0;
			//计算出鼠标坐标相对于block坐标的间距 
			var offLX = pageX - offX;
			var offLY = pageY - offY;
			if (!document.onmousemove) {
				document.onmousemove = function() {
					container.style.left = event.clientX - offLX; //设置block的X坐标 
					container.style.top = event.clientY - offLY; //设置block的Y坐标 
				}
			}
		}
		document.onmouseup = function() {
			document.onmousemove = null;
		} //鼠标弹起 
注:横向移动,下面代码控制
container.style.left = event.clientX - offLX; //设置block的X坐标 
   纵向移动,下面代码控制
container.style.top = event.clientY - offLY; //设置block的Y坐标 
两行代码全部加上,空间中自由移动,屏蔽第一个行,纵向移动,反之横向移动

 
 

你可能感兴趣的:(js)