JavaScript: the entire page click event, event.ClientX obtain the coordinates of the click

Execute the following code to the click event was supposed to implement the entire page, but in fact only part of the black box only click event, because body hold up to rely on the content.

<!DOCTYPE html>
<html>
<head>
	<title>学习事件</title>
<style type="text/css">
	body{
	border: 1px solid black;
}
</style>
<script type="text/javascript">
window.onload = function(){
	document.body.onclick = function(){
		alert("something");
	}
};
</script>
</head>
<body>
<input type="button" value="点击">
</body>
</html>

 If you want to implement the click event of the entire page, then get rid of the body, directly document.onclick, no matter where you click, a click event will touch

<!DOCTYPE html>
<html>
<head>
	<title>学习事件</title>
<style type="text/css">
	body{
	border: 1px solid black;
}
</style>
<script type="text/javascript">
window.onload = function(){
	document.onclick = function(){
		alert("something");
	}
};
</script>
</head>
<body>
<input type="button" value="点击">
</body>
</html>

 Note: button no practical effect, just to distraction body introduced

Here Gets click of the mouse position, very simple, adding event.clientX and event.clientY

<!DOCTYPE html>
<html>
<head>
	<title>学习事件</title>
<style type="text/css">
	body{
	border: 1px solid black;
}
</style>
<script type="text/javascript">
window.onload = function(){
	document.onclick = function(){
		alert("("+event.clientX+","+event.clientY+")");
	}
};
</script>
</head>
<body>
<input type="button" value="点击">
</body>
</html>

Finally, the function onclick event parameters can be passed, consider the following compatibility

<!DOCTYPE html>
<html>
<head>
	<title>学习事件</title>
<style type="text/css">
	body{
	border: 1px solid black;
}
</style>
<script type="text/javascript">
window.onload = function(){
	document.onclick = function(ev){
		var oEvent = ev || event;//考虑了兼容性
		alert("("+oEvent.clientX+","+oEvent.clientY+")");
	}
};
</script>
</head>
<body>
<input type="button" value="点击">
</body>
</html>

 

Published 126 original articles · won praise 7 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_36880027/article/details/104349260