js实现可拖动DIV的方法

随着时代的变化,越来越感觉到js的重要性,js不仅可以做web页面(如Ext框架),还可以做一些web的特效,这些特效不仅兼容PC,而且兼容手机端,毕竟是基于浏览器的,和平台没关系。现在微软的windows8 系统的App都可以用js开发了,大家有时间可以去尝试一下。

现在切入正题,说一下js 实现可拖动Div.实现这个功能我们先说一下思路:

1.捕捉鼠标div的mousedown事件

2.捕捉 document的   mousemove事件

3.取消事件

然后我们看一下代码:

复制代码 代码如下:


function Drag(id) {
            var $ = function (flag) {
                return document.getElementById(flag);
            }
            $(id).onmousedown = function (e) {
                var d = document;
                var page = {
                    event: function (evt) {
                        var ev = evt || window.event;
                        return ev;
                    },
                    pageX: function (evt) {
                        var e = this.event(evt);
                        return e.pageX || (e.clientX + document.body.scrollLeft - document.body.clientLeft);
                    },
                    pageY: function (evt) {
                        var e = this.event(evt);
                        return e.pageY || (e.clientY + document.body.scrollTop - document.body.clientTop);

},
                    layerX: function (evt) {
                        var e = this.event(evt);
                        return e.layerX || e.offsetX;
                    },
                    layerY: function (evt) {
                        var e = this.event(evt);
                        return e.layerY || e.offsetY;
                    }
                }            
                var x = page.layerX(e);
                var y = page.layerY(e);       
                if (dv.setCapture) {
                    dv.setCapture();
                }
                else if (window.captureEvents) {
                    window.captureEvents(Event.MOUSEMOVE | Event.MOUSEUP);
                }
                d.onmousemove = function (e) {                   
                    var tx = page.pageX(e) - x;
                    var ty = page.pageY(e) - y;
                    dv.style.left = tx + "px";
                    dv.style.top = ty + "px";
                }
                d.onmouseup = function () {
                    if (dv.releaseCapture) {
                        dv.releaseCapture();
                    }
                    else if (window.releaseEvents) {
                        window.releaseEvents(Event.MOUSEMOVE | Event.MOUSEUP);
                    }
                    d.onmousemove = null;
                    d.onmouseup = null;
                }
            }
        }

代码分析:

1.

获取div对象

复制代码 代码如下:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wdwgxg.html