JS实现的简单拖拽功能示例

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>js实现拖拽</title>
    <style>
      #water{
        width:400px;
        height:188px;
        background-color: #ff6600;
      }
      #water:hover{
        cursor: pointer;
      }
    </style>
  </head>
  <body>
    <div id="water"></div>
    <script>
      dragInit("water");//调用
      //拖拽初始化
      function dragInit(id){
        var $div = document.getElementById(id);
        var style = {
          position: "absolute",
          left: "0",
          top: "0"
        }
        for(var k in style){
          $div.style[k] = style[k];//设置关键css
        }
        $div.onmousedown = function(e){//鼠标按键按下
          e = e || window.event;
          var x = e.clientX - $div.offsetLeft;//鼠标到左上角的距离信息, 固定不变
          var y = e.clientY - $div.offsetTop;
          document.onmousemove = function(e){//鼠标移动
            e = e || window.event;
            var L = e.clientX - x;
            var T = e.clientY - y;
            var pW = document.documentElement.clientWidth;//页面宽度
            var pH = document.documentElement.clientHeight;
            var divW = $div.offsetWidth;//Dom宽度
            var divH = $div.offsetHeight;
            // 范围限定
            if(L < 0){
              L = 0;
            }
            if(T < 0){
              T = 0;
            }
            if(L > pW - divW){
              L = pW - divW;
            }
            if(T > pH - divH){
              T = pH - divH;
            }
            // 范围限定 end
            //$div.style.left = L + "px";// 注释这句只能上下移动
            $div.style.top = T + "px";// 注释这句只能左右移动
          };
          document.onmouseup = function(e){//鼠标按键松开
            document.onmousemove = null;
          };
        };
      }
    </script>
  </body>
</html>

猜你喜欢

转载自blog.csdn.net/cnicfhnui/article/details/107516939