[javascript]一種相容性比較好的簡單拖拽

來源:互聯網
上載者:User

標籤:

作為一個馬上要找工作、非電腦專業、熱愛前端的大四狗,最近開始瘋狂寫demo、看書,準備九、十月份的校招。

晚上用js實現了一個比較簡單(low)的拖拽效果,初步測試相容性還是不錯的,於是寫一段小博文記錄下~大神求輕噴

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Document</title>    <style>        #box {            width: 100px;            height: 100px;            background: red;            position: absolute;        }    </style></head><body>    <div id="box"></div>    <script>        window.onload = function (){            var disX = 0;            var disY = 0;            var oBox = document.getElementById("box");            oBox.onmousedown = function (ev){                var oEvent = ev || event;                oBox.style.cursor = "move";                disX = oEvent.clientX - oBox.offsetLeft;                disY = oEvent.clientY - oBox.offsetTop;                document.onmousemove = function (ev){                    var oEvent = ev || event;                    var theLeft = oEvent.clientX - disX;                    var theTop = oEvent.clientY - disY;                                        // 禁止使用者從瀏覽器左框拖出                    if (theLeft < 0) {                        theLeft = 0;                    } else if (theLeft > document.documentElement.clientWidth-                        oBox.offsetWidth) {                        theLeft = document.documentElement.clientWidth-                        oBox.offsetWidth;                    } else if (theTop < 0) {                        theTop = 0;                    } else if (theTop > document.documentElement.clientHeight-                        oBox.offsetHeight) {                        theTop = document.documentElement.clientHeight-                        oBox.offsetHeight;                    }                    oBox.style.left = theLeft + ‘px‘;                    oBox.style.top = theTop + ‘px‘;                }            }            document.onmouseup = function (){                document.onmousemove =null;            }         // 視窗調整大小時的處理方法            window.onresize = function (){                oBox.style.left = document.documentElement.clientWidth/2-oBox.offsetWidth/2 + ‘px‘;                oBox.style.top = document.documentElement.clientHeight/2-oBox.offsetHeight/2 + ‘px‘;            }            // 相容firefox 3.6.19            return false;        }    </script></body></html>

 

[javascript]一種相容性比較好的簡單拖拽

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.