js面向对象思想封装拖拽功能,兼容pc和移动端

我们在开发项目过程中,很可能会碰到页面上某块需要可以拖拽移动的功能需求,网上已经有不少前辈分享了相关功能的案例,插件或者代码,但是考虑到项目功能需求,我们可能仅需要实现拖拽移动功能就可以,不需要其他功能,而网上很多插件往往附带了其他功能需求。这里笔者仅对拖拽移动这一功能进行实现,并且采用了js面向对象的思想来实现,请各位读者品鉴,有不足之处还望指正。

function Drag(dom) {
    this.dom = document.getElementById(dom);
    this.flag = false;
    var self = this;
    var sty = null;
    if(window.getComputedStyle) {
        sty = window.getComputedStyle(self.dom, null); // 非IE
    } else {
        sty = self.dom.currentStyle; // IE
    }
    this.maxLeft = document.documentElement.clientWidth - sty.width.split('px')[0]; //当前元素可移动的最大左偏移
    this.maxTop = document.documentElement.clientHeight - sty.height.split('px')[0]; //当前元素可移动的最大上偏移

    self.dom.addEventListener("mousedown", function(e) {
        self.down(self);
    }, false);
    self.dom.addEventListener("touchstart", function(e) {
        self.down(self);
    }, false)

}
//按下
Drag.prototype.down = function(self) {
    self.flag = true;
    var touch;
    if(event.touches) {
        touch = event.touches[0];
    } else {
        touch = event;
    }
    var offLeft = touch.clientX - self.dom.offsetLeft;//当前点击点相对元素左边框的距离
    var offTop = touch.clientY - self.dom.offsetTop;//当前点击点相对元素上边框的距离

    self.dom.addEventListener("mousemove", function() {
        self.move(self,offLeft,offTop);
    }, false);
    self.dom.addEventListener("touchmove", function() {
        self.move(self,offLeft,offTop);
    }, false)
    document.body.addEventListener("mouseup", function() {
        self.end(self);
    }, false);
    self.dom.addEventListener("touchend", function() {
        self.end(self);
    }, false);
}
//移动
Drag.prototype.move = function(self,offLeft,offTop) {
    if(self.flag) {
        var touch;
        if(event.touches) {
            touch = event.touches[0];
        } else {
            touch = event;
        }
        var endX = touch.clientX - offLeft;//元素移动后的left距离
        var endY = touch.clientY - offTop;//元素移动后的top距离
        if(endX <= 0) {
            endX = 0;
        } else if(endX >= self.maxLeft) {
            endX = self.maxLeft;
        }
        if(endY <= 0) {
            endY = 0;
        } else if(endY >= self.maxTop) {
            endY = self.maxTop;
        }

        self.dom.style.left = endX + "px";
        self.dom.style.top = endY + "px";

        //阻止页面的滑动默认事件
        document.addEventListener("touchmove", function() {
            event.preventDefault();
        }, false);
    }
}
//释放
Drag.prototype.end = function(self) {
    self.flag = false;
}

以一个id为box的div为例,实现该功能时只需要在window.onload内按如下方式声明就可以:

window.onload = function(){
    new Drag('box');
}

在移动端和PC网页上均可以达到理想效果,读者感兴趣可以自行尝试。
文件下载处:
感兴趣的读者可以直接去下载js文件

你可能感兴趣的:(JavaScript)