關於移動div的具體實現(js)

來源:互聯網
上載者:User

標籤:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>移動框練習</title>    <style type = "text/css">        #big{width: 300px;height: 200px;position: absolute;top: 200px;left: 300px;background: #ccc;}        h1{width: 200px;height: 50px;line-height: 50px;text-align: center;background: orange;margin: 0 auto; cursor: move;}    </style></head><body>    <div id="big">        <h1 class="titl"></h1>    </div>    <script type="text/javascript">        //通過父元素擷取到指定想要擷取的元素。        function getClass(clsName,parent){            var oParent = parent?document.getElementById(parent):document;            var oH1 = oParent.getElementsByClassName(clsName)[0];            return oH1;        }        window.onload = drag;        //給h1添加按住的事件。        function drag(){            var h1Node = getClass("titl","big");            h1Node.onmousedown = fnDown;        }        //通過函數來擷取指標的位置。        function fnDown(event) {            event = event || window.event;            var oDiv = document.getElementById("big"),                //游標按下時游標和面板之間的距離。                disX = event.clientX-oDiv.offsetLeft;                disY = event.clientY-oDiv.offsetTop;            document.onmousemove = function(event) {                event = event || window.event;                fnMove(event,disX,disY);            }            document.onmouseup = function(){                document.onmousemove = null;            }        }        function fnMove(e,posX,posY) {            var oDiv = document.getElementById("big"),                l = e.clientX-posX,                t = e.clientY-posY,                winW = document.documentElement.clientWidth || document.body.clientWidth,                winH = document.documentElement.clientHeight || document.body.clientHeight,                maxW = winW-oDiv.offsetWidth,                maxH = winH-oDiv.offsetHeight;            if (l<0) {                l=10;            } else if(l>maxW){                l=maxW;            }            if (t<0) {                t=10;            } else if(t>maxH){                t=maxH;            }            oDiv.style.left = l+"px";            oDiv.style.top = t+"px";        }    </script></body></html>

 

關於移動div的具體實現(js)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.