鼠标行为

1、坐标系

clientX/Y 鼠标位置相对于当前可视区域的坐标(不包含滚动条的距离)
layerX/Y 同pageX/pageY相同,IE11以下同clientX/Y
screenX/Y 鼠标位置相对于屏幕的坐标
x/y 同clientX/Y相同,FF老版不支持
pageX/pageY 鼠标位置相对于当前文档的坐标(包含滚动条的距离),IE9以下不支持
offsetX/Y 鼠标位置相对于块元素的坐标(包括边框,safari不包括边框)

<style type="text/css">
    .box {
        width: 100px;
        height: 100px;
        background-color: orange;
    }
</style>
<body>
<div class="box"></div>

<script type="text/javascript">
var box = document.getElementsByTagName('box')[0];

// 利用冒泡机制的 事件委托
document.onclick = function(e) {
    var e = e || window.event;
    console.log(e);

    console.log(e.clientX, e.clientY);
    console.log(e.x, e.y);

    console.log(e.screenX, e.screenY);

    console.log(e.pageX, e.pageY);
    console.log(e.layerX, e.layerY);
}
</script>

2、获取坐标封装

// 获取坐标封装
function pagePos(e) {
    // 获取滚动距离
    var sLeft = getScrollOffset().left,
        sTop = getScrollOffset().top,
        // 获取文档偏移
        cLeft = document.documentElement.clientLeft || 0,
        cTop = document.documentElement.clientTop || 0;

    return {
        X: e.clientX + sLeft - cLeft,
        Y: e.clientY + sTop - cTop
    }
}

3、拖拽mousedown mouseup mousemove

var box = document.getElementsByClassName('box')[0];
elemDrag(box);

// 封装拖拽函数
function elemDrag(el) {
    var x,
        y;

    addEvent(el, 'mousedown', function(e){
        var e = e || window.event;
        x = pagePos(e).X - getStyles(el, 'left');
        y = pagePos(e).Y - getStyles(el, 'top');

        addEvent(document, 'mousemove', mouseMove);
        addEvent(document, 'mouseup', mouseUp);

        // 去掉冒泡
        cancelBubble(e);
        // 取消默认事件
        stopEvent(e);
    });

    function mouseMove(e) {
        var e = e || window.event;
        el.style.left = pagePos(e).X - x + 'px';
        el.style.top = pagePos(e).Y - y + 'px';
    }

    function mouseUp(e) {
        var e = e || window.event;
        removeEvent(document, 'mousemove', mouseMove);
        removeEvent(document, 'mouseup', mouseUp);
    }
}