JS获取鼠标位置、当前元素所在位置

JS获取鼠标位置,当前元素的top left width height




//获取元素的绝对位置,大小。 参数js对象
function getElAbsolute(elem) {
    var t = elem.offsetTop;
    var l = elem.offsetLeft;
    var w = elem.offsetWidth;
    var h = elem.offsetHeight;
    elem = elem.offsetParent;
    while (elem) {
        t += elem.offsetTop;
        l += elem.offsetLeft;
        elem = elem.offsetParent;
    };
    return {
        top: t,
        left: l,
        width: w,
        height: h
    };
}
//兼容各种浏览器的,获取鼠标真实位置
function mousePosition(ev) {
    if (!ev) ev = window.event;
    if (ev.pageX || ev.pageY) {
        return { x: ev.pageX, y: ev.pageY };
    }
    return {
        x: ev.clientX + document.documentElement.scrollLeft - document.body.clientLeft,
        y: ev.clientY + document.documentElement.scrollTop - document.body.clientTop
    };
}

你可能感兴趣的:(Js)