JavaScript實現網頁元素的拖拽效果

來源:互聯網
上載者:User

下面的頁面中放了兩個div,可以通過滑鼠拖拽這兩個元素到任意位置。



實現該效果的HTML頁面代碼如下所示:

                <script type="text/javascript" src="js/mylib.js"></script>    <script type="text/javascript">        window.onload = function() {            var obj1 = createDraggableObject();            var obj2 = createDraggableObject();            obj1.init($('xixi'));            obj2.init($('haha'));        };    </script>    Fuck!    Shit!

外部JavaScript檔案代碼如下所示:

/** * 根據id擷取頁面元素 * @param id * @returns {HTMLElement} */function $(id) {    return document.getElementById(id);}/** * 建立可拖拽對象的Factory 方法 */function createDraggableObject() {    return {        obj: null, left: 0, top: 0,        oldX: 0, oldY: 0, isMouseLeftButtonDown: false,        init: function (obj) {            this.obj = obj;var that = this;            this.obj.onmousedown = function (args) {                var evt = args || event;                this.style.zIndex = 100;                that.isMouseLeftButtonDown = true;                that.oldX = evt.clientX;                that.oldY = evt.clientY;if (this.currentStyle) {                    that.left = parseInt(this.currentStyle.left);                    that.top = parseInt(this.currentStyle.top);                }                else {                    var divStyle = document.defaultView.getComputedStyle(this, null);                    that.left = parseInt(divStyle.left);                    that.top = parseInt(divStyle.top);                }            };            this.obj.onmousemove = function (args) {                that.move(args || event);            };            this.obj.onmouseup = function () {                that.isMouseLeftButtonDown = false;                this.style.zIndex = 0;            };        },        move: function (evt) {            if (this.isMouseLeftButtonDown) {                var dx = parseInt(evt.clientX - this.oldX);                var dy = parseInt(evt.clientY - this.oldY);                this.obj.style.left = (this.left + dx) + 'px';                this.obj.style.top = (this.top + dy) + 'px';            }        }    };}


聯繫我們

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