Blogger Information
Blog 38
fans 0
comment 3
visits 43831
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
js基础学习-实时获取鼠标在div中的【坐标】
意外的博客
Original
708 people have browsed it
<!DOCTYPE html>
<html>
<head>
	<title>实时获取鼠标在div中的坐标</title>
	<style type="text/css">
		div{
			width: 500px;height: 400px;
			margin: 100px auto 10px;
			border: 1px solid red;
		}
		p{
			width: 500px;height: 40px;
			border:1px solid green;
			margin: 0 auto;
			text-align:center;
			line-height: 40px;
		}
	</style>
</head>
<body>
	<div id="main"></div>
	<p>坐标为:<b id="show">(0,0)</b></p>

<script type="text/javascript">
	window.onload=function(){
		var divobj=document.getElementById('main');
		var bobj=document.getElementById('show');
		divobj.onmousemove=function(event){
			// 浏览器兼容
			var e=event || window.event
			//获取鼠标的坐标
			var m_x=e.clientX	//鼠标获取x轴坐标
			var m_y=e.clientY	//鼠标获取y轴坐标
			//获取div的坐标,一左上角的那个点为准,这个点是和鼠标的坐标相等的;
			var d_x=this.offsetLeft;	//offsetLeft:html元素相对于文档的x轴位置
			var d_y=this.offsetTop;	//offsetTop:html元素相对于文档的y轴位置

			// 鼠标的坐标减去这个方框左上角的那个坐标为(0,0)开始;
			// 理解为;有一个100*100的方框在一个平面中,左上角的那个点和鼠标开始重合,那么就是(0,0)坐标的开始,右下角那个点的坐标就为(100,100)
			x = m_x - d_x;
			y = m_y - d_y;
			bobj.innerHTML='('+x+','+y+')'
		}
	}
</script>
</body>
</html>


Correction status:Uncorrected

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post