欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

js 鼠标拖拽事件

程序员文章站 2022-07-14 09:40:50
...

第一步:获取元素,绑定按下事件

var red = document.getElementById('red'); //获取红色泡
var mouseOffsetX = 0, mouseOffsetY = 0; //初始定义偏移值
var isDrag = false;         //是否可拖动
red.addEventListener('mousedown', function (e) {//鼠标按下
    var e = e || window.event;
    mouseOffsetX = e.pageX - red.offsetLeft; //鼠标指针位置减去元素的左边距
    mouseOffsetY = e.pageY - red.offsetTop;
    isDrag = true;
});
第二步:鼠标移动
//鼠标移动
document.onmousemove = function (e) {//鼠标移动e
    var e = e || window.event;
    var mouseX = e.pageX;
    var mouseY = e.pageY;
    var moveX = 0, moveY = 0;
    if (isDrag === true) {
        moveX = mouseX - mouseOffsetX; //移动的距离等于鼠标指针减去上面获取的差值
        moveY = mouseY - mouseOffsetY;
        //限定移动范围
        var PW = document.documentElement.clientWidth;//窗口的宽高
        var PH = document.documentElement.clientHeight;

        var redW = red.offsetWidth; //元素红色泡泡的自身的宽高
        var redH = red.offsetHeight;

        var maxX = PW - redW; //最大的宽度为窗口可视区宽减去自身的宽
        var maxY = PH - redH;
        moveX = Math.min(maxX, Math.max(0, moveX));// 取值范围
        moveY = Math.min(maxY, Math.max(0, moveY));
        red.style.left = moveX + 'px';
        red.style.top = moveY + 'px';

第三步:鼠标移开,将可被拖拽设置为false即可
//鼠标松开
document.onmouseup = function () {
    isDrag = false;
};