今天做项目用到了event.clientX和event.clientY,给元素定位,用定位的时候,让top和left等于事件元素的的坐标

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>javascript的动态显示</title>
		<style>
			a{
				display:block;
				height:50px;
				width:50px;
			}
		</style>
		
	</head>
	<body>
		<a href="http://www.baidu.com" title="baidu">百度</a>
		<a href="http://www.baidu.com" title="baidu">百度</a>
		<a href="http://www.baidu.com" title="baidu">百度</a>
		<a href="http://www.baidu.com" title="baidu">百度</a>
		<script>
			(function(){
				var as=document.getElementsByTagName("a");
				for(var i=0;i<as.length;i++){
					as[i].onmouseover=mouseover;
				}
				function mouseover(){
					var div=document.createElement("div");
					div.style.position="absolute";
					console.log(window.event.clientY);
					div.style.top=window.event.clientY+'px';
					console.log(div.style.top);
					div.style.left=window.event.clientX+'px';
					div.innerHTML="链接到百度";
					document.body.appendChild(div);
				}
			})(window);
		</script>
	</body>
</html>

  正确写法是:div.style.left=window.event.clientX+'px';要加上单位就可以了,刚开始不加单位,打印不出来任何东西,加上单位打印出坐标值

posted on 2016-09-06 14:04  太阳花0525  阅读(1683)  评论(0编辑  收藏  举报