javascript获取页面鼠标光标位置

function mousePosition(evt){
if(evt.pageX || evt.pageY){
return {x:evt.pageX,y:evt.pageY};
}
return {
x:evt.clientX + document.body.scrollLeft - document.body.clientLeft,
y:evt.clientY + document.body.scrollTop - document.body.clientTop
};
}
function mouseMove(evt){
var e = evt || window.event;
var m = mousePosition(evt);
document.getElementById('xx').value= m.x;
document.getElementById('yy').value= m.y;
}
// document.onmousemove = mouseMove;
document.onmousemove = function(e){
var e = e || window.event;
var m = mousePosition(e);
document.getElementById('xx').value= m.x;
document.getElementById('yy').value= m.y;
}
</script>
<input id="xx" type="text"/>
<input id="yy" type="text"/>

在线演示

假如使用的是jquery的话,则直接使用jQuery的e.pageX和e.pageY则行,里面已经封装好了。

最近的一个项目用到了这个JS,需要判断鼠标光标是否移入了某个块的区域,当进入时,则停止循环滚动,当出来时,则继续滚动

//两秒后调用
var dteamPos = $(".dteam-con-pos");
var dteamList = $("#dteamList");
function AutoScroll(){ //循环向左滚动
var _scroll = $("#firstDteam > ul");
//ul往左边移动200px
_scroll.filter(':not(:animated)').animate({marginLeft:"-200px"},1000,function(){
//把第一个li丢最后面去
_scroll.css({marginLeft:0}).find("li:first").appendTo(_scroll);
});
var _scroll2 = $("#secondDteam > ul");
//ul往左边移动200px
_scroll2.filter(':not(:animated)').animate({marginLeft:"-200px"},1000,function(){
//把第一个li丢最后面去
_scroll2.css({marginLeft:0}).find("li:first").appendTo(_scroll2);
});
var _scroll3 = $("#thirdDteam > ul");
//ul往左边移动200px
_scroll3.filter(':not(:animated)').animate({marginLeft:"-200px"},1000,function(){
//把第一个li丢最后面去
_scroll3.css({marginLeft:0}).find("li:first").appendTo(_scroll3);
});
}
var flag = 1;
var _scrolling;
if(flag == 1){
_scrolling=setInterval(AutoScroll,2000);
}

var index;
$(".dteam-con").mouseover(function(e){
// e.stopPropagation();
var x = 10;
var y = 10;
var self = $(this);
var _html = self.html();
dteamPos.html('');
dteamPos.html(_html);
if(dteamPos.html() != ''){
clearInterval(_scrolling);
}
var dteamLeft = self.offset().left - x;
var dteamTop = self.offset().top - y;
dteamPos.css({
top:dteamTop,
left:dteamLeft,
display:"block"
})
});

var dteamList = $('#dteamList"), dteamPost = $(".dteamPos"), dteamListTop, dteamlistHeight, dteamlistBottom;
function resetPos(evt){
dteamListTop = dteamList.offset().top;
dteamlistHeight = dteamList.height();
dteamlistBottom = parseInt(dteamListTop + dteamlistHeight);
if((evt.pageY <dteamListTop) || (evt.pageY > dteamlistBottom)){
if(dteamPos.html() != ''){
dteamPos.html('');
dteamPos.hide();
_scrolling=setInterval(AutoScroll,2000);
}
}
}
$(document).mousemove(function(e){
// e.stopPropagation();
resetPos(e);
});
$(window).on("resize",function(e){
resetPos(e);
})

代码各种复杂

原文链接:javascript获取页面鼠标光标位置 版权所有,转载时请注明出处,违者必究。
注明出处格式:前端开发博客 (http://caibaojian.com/pagex-pagey.html)

发表评论

请登录后发表评论: