js获取鼠标的坐标

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xuehu837769474/article/details/81947673
1、JavaScript实现

X:<input id="xxx" type="text" /> Y:<input id="yyy" type="text" />

    function mousePosition ( ev ) {
        if ( ev.pageX || ev.pageY ) {
            return { x : ev.pageX, y : ev.pageY };
        }
        return {
            x : ev.clientX + document.body.scrollLeft - document.body.clientLeft,
            y : ev.clientY + document.body.scrollTop - document.body.clientTop
        };
    };
function mouseMove ( ev ) {
    ev = ev || window.event;
    var mousePos = mousePosition(ev);
    document.getElementById('xxx').value = mousePos.x;
    document.getElementById('yyy').value = mousePos.y;
}
document.onmousemove = mouseMove;

2、jQuery实现

$('#ele').click(function ( event ) {
    //获取鼠标在图片上的坐标
    console.log('X:' + event.offsetX + '\n Y:' + event.offsetY);
    //获取元素相对于页面的坐标
    console.log('X:' + $(this).offset().left + '\n Y:' + $(this).offset().top);
});
展开阅读全文

没有更多推荐了,返回首页