获取鼠标坐标

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>获取鼠标坐标</title>
		<style>
			#mousedot{width:20px;height:20px;background:#ccc;position:absolute;top:0;left:0;}
		</style>
	</head>
	<body>
		<div id="mousedot"></div>
	</body>
</html>
<script>
	var mousedot=document.getElementById("mousedot");
	
	function mousePosition(e){
		if(e.pageX){
			//ie9及以上,其他浏览器均支持pageX属性
return {x:e.pageX,y:e.pageY};
		}else{
			return{
				x:e.clientX + document.body.scrollLeft - document.body.clientLeft,
				y:e.clientY + document.body.scrollTop - document.body.clientTop,
			}
		}
	}
	function mousemove(e){
		var e=e|| window.event;
		var mosusepos=mousePosition(e);
		mousedot.style.left=mosusepos.x-mousedot.clientWidth/2+"px";
		mousedot.style.top=mosusepos.y-mousedot.clientHeight/2+"px";
	}
	
	document.onmousemove=mousemove;
		
</script>

1、坐标值:

  pageX:触发点相对于文档左上角的位置

  clientX:触发点相对于浏览器左上角的位置

  screenX:触发点相对于屏幕左上角的位置

2、原生js获取元素的宽高:

  clientWidth、clientHeight 元素可视区的大小

 

posted @ 2017-08-10 11:09  偶多克  阅读(241)  评论(0编辑  收藏  举报