天天看点

js原生代码实现鼠标拖拽效果

闲来无事,用js原生代码写了简单的鼠标拖拽效果,话不多说,代码如下:

// A code block

<style type="text/css">
			#box{width: 100px;height: 100px;background: red;position: absolute;left: 0;top: 0;}
		</style>
	</head>
	<body>
		<div id="box">hello world</div>
	</body>
    <script type="text/javascript">
           /*****让滑块随鼠标移动***/
          // 准备:获取节点box
          var boxObj = document.getElementById('box');
          // 1 给box绑定鼠标按下事件
          boxObj.onmousedown = function(eve){
             // 2 获取鼠标点击时相对于box元素的位置(offsetX,offsetY距离) 
             var offX = eve.offsetX;
             var offY = eve.offsetY;
           //  console.log(offX,offY);
            // 3 给document绑定鼠标移动事件
            document.onmousemove = function(e){
                // 4 获取鼠标的相对于客户端的位置(clientX,clientY);
                var cliX = e.clientX;
                var cliY = e.clientY;
                 // 5 计算滑块的left和top的定位距离
                var l = cliX-offX;
                var t = cliY-offY;
               /******目标:设置滑块的边界********/
                 // A 获取可视区域的宽度和高度
                 var docuW = document.documentElement.clientWidth;  // clientWidth  == width+padding
                 var docuH  = document.documentElement.clientHeight;
                // B 计算出滑块在Y轴的最大和最小值
                if(t<0) t=0;
                // 大的说明要出去了,就给它可视区域的高度-本身的高度
                if(t>(docuH-boxObj.clientHeight)) t=docuH-boxObj.clientHeight;
                if(l<0) l=0;  // 不能从左边出去
                if(l>(docuW-boxObj.clientWidth)) l = docuW-boxObj.clientWidth;
                 
                 
                // 6 设置box位置
                 boxObj.style.top = t+'px';
                 boxObj.style.left = l+'px';
              //  console.log(cliX,cliY);
            }
                //清除默认行为,不让文字选中
                 eve.preventDefault();
          }

          // 7 清除document的移动事件,防止鼠标弹起,滑块还跟着鼠标动
        //   boxObj.onmouseup = function(){
        //       document.onmousemove = null;
        //   }
        // 优化的写法
         document.onmouseup = function(){
              document.onmousemove = null;
          }
      
         


		
		
	</script>
           

继续阅读