当我向下滚动或向上滚动时,如何获得鼠标位置
我试过这个
$(document).mousemove(function(event) {
captureMousePosition(event);
}).scroll(function(event) {
xMousePos = event.pageX + $(document).scrollLeft();
yMousePos = event.pageY + $(document).scrollTop();
window.status = "x = " + xMousePos + " y = " + yMousePos;
});
function captureMousePosition(event){
xMousePos = event.pageX;
yMousePos = event.pageY;
window.status = "x = " + xMousePos + " y = " + yMousePos;
}
但没有用,我想要鼠标相对于页面顶部的确切位置而不是窗口(框架)
答案 0 :(得分:11)
我们无法在滚动中获取鼠标当前位置我们可以获得它相对于最后位置滚动了多少 所以改成了:
var xMousePos = 0;
var yMousePos = 0;
var lastScrolledLeft = 0;
var lastScrolledTop = 0;
$(document).mousemove(function(event) {
captureMousePosition(event);
})
$(window).scroll(function(event) {
if(lastScrolledLeft != $(document).scrollLeft()){
xMousePos -= lastScrolledLeft;
lastScrolledLeft = $(document).scrollLeft();
xMousePos += lastScrolledLeft;
}
if(lastScrolledTop != $(document).scrollTop()){
yMousePos -= lastScrolledTop;
lastScrolledTop = $(document).scrollTop();
yMousePos += lastScrolledTop;
}
window.status = "x = " + xMousePos + " y = " + yMousePos;
});
function captureMousePosition(event){
xMousePos = event.pageX;
yMousePos = event.pageY;
window.status = "x = " + xMousePos + " y = " + yMousePos;
}
它可以工作并且正在使用多种浏览器......
无论如何感谢所有人:)
答案 1 :(得分:-3)
我没试过你尝试过:
$(document).ready(function(){
$(document).scroll(function(e){
$('#status').html(e.pageX +', '+ e.pageY);
});
});