首页 > 代码库 > html--鼠标控制DIV移动

html--鼠标控制DIV移动

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>鼠标控制DIV移动</title>
        <script type="text/javascript">
              
              var _IsMousedown = 0;
              var _ClickLeft = 0;
              var _ClickTop = 0;
            function moveInit(evt) {
              _IsMousedown = 1;
              var obj = getObjById(moveDiv);
              _ClickLeft = evt.clientX-obj.offsetLeft;
              _ClickTop = evt.clientY-obj.offsetTop;

            }

            function startMove(evt) {
              if(_IsMousedown == 0){
                  return;
              }
              var obj = getObjById(moveDiv);
              obj.style.left = evt.clientX - _ClickLeft;
              obj.style.top = evt.clientY - _ClickTop;

            }

            function stopMove() {
              _IsMousedown = 0;

            }

            function getObjById(id) {

                return document.getElementById(id);

            }
        </script>

        <style type="text/css" rel="stylesheet">
            #movediv {
                width: 100px;
                height: 100px;
                position: absolute;
                border: 1px solid #000;
                background: #EAEAEA;
            }
        </style>
    </head>
    <body>
        <div id="moveDiv" style="left:20px;top:20px;"

        onm ousedown="moveInit(event);"

        onm ousemove="startMove(event)"

        onm ouseup="stopMove()"

        onm ouseout="stopMove()">

        </div>
    </body>
</html>

 

html--鼠标控制DIV移动