document.onclick = function (event) {
//var event = event || window.event;
var event = eventUtil.getEvent(event);
console.log("client: " + event.clientX + "--" + event.clientY);//浏览器窗口
//page有兼容问题 client没有 我们可以用client来计算page
var pageX = eventUtil.getPageX(event);
var pageY = getPageY(event);
console.log("page: " + event.pageX + "--" + event.pageY);//页面上,如果页面有滚出也要加上
console.log("screen: " + event.screenX + "--" + event.screenY);//整个屏幕
};
//其中 最常用的是page
function getPageX(event) {
return event.pageX || event.clientX + document.documentElement.scrollLeft;
}
function getPageY(event) {
return event.pageY || event.clientY + document.documentElement.scrollTop;
}
<script>
var box = document.getElementById("box");
//计算鼠标在盒子中的位置 就是 鼠标在页面上的位置-盒子在页面上的位置
//鼠标在盒子中移动的时候 把鼠标的位置写在盒子里
box.onmousemove = function (event) {
var event = event || window.event;
//获取鼠标在页面上的位置
var pageX = event.pageX || event.clientX + document.documentElement.scrollLeft;
var pageY = event.pageY || event.clientY + document.documentElement.scrollTop;
//盒子在页面上的位置
//box.offsetLeft
//box.offsetTop
//计算 鼠标 在盒子中的位置
var boxX = pageX - box.offsetLeft;
var boxY = pageY - box.offsetTop;
box.innerHTML = boxX + "---" + boxY;
};
</script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<button id="btn">按钮</button>
<script>
var btn = document.getElementById("btn");
btn.onclick = function (event) {
alert("按钮被点击啦");
var event = event || window.event;
event.stopPropagation();
};
document.onclick = function () {
alert("文档被点击了");
};
</script>
</body>
</html>
封装
<script>
var btn = document.getElementById("btn");
btn.onclick = function (event) {
alert("按钮被点击啦");
var event = event || window.event;
stopPropagation(event);
};
function stopPropagation(event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
}
</script>
var eventUtil = {
getEvent: function (event) {
return event || window.event;
},
getPageX: function (event) {
return event.pageX || event.clientX + document.documentElement.scrollLeft;
},
getPageY: function (event) {
return event.pageY || event.clientY + document.documentElement.scrollTop;
},
stopPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
getTarget: function (event) {
return event.target || event.srcElement;
}
};