鼠标跟随div移动

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			#box1{
				width: 10px;
				height: 10px;
				background-color: red;
				/* 设计位置开启绝对定位 */
				position: absolute;
			}
		</style>
		<script type="text/javascript">
			window.onload = function(){
				// div跟着鼠标移动
				var box1 = document.getElementById("box1");
				
				document.onmousemove = function(event){
					// 兼容
					event = event || window.event;
					// 获取滚动条滚动距离
					// chrome认为浏览器滚动条是body的
					// 火狐等认为是html的
					var st = document.body.scrollTop||document.documentElement.scrollTop;
					var sl = document.body.scrollLeft||document.documentElement.scrollLeft;
					// var st = document.documentElement.scrollTop;
					console.log(st);
					
					// 获取鼠标坐标
					// clientX clientY可见窗口
					// var left = event.clientX;
					// var top = event.clientY;
					// pageX pageY整个页面不兼容IE8
					// var left = event.pageX;
					// var top = event.pageY;
					var left = event.clientX;
					var top = event.clientY;
					// 设置div偏移量
					box1.style.left = left + sl + "px";
					box1.style.top = top + st + "px";
				};
			};
		</script>
	</head>
	<body style = "height:1000px;width:1000px">
		<div id="box1">
			
		</div>
	</body>
</html>

上一篇:flex 布局


下一篇:CSS3伪元素选择器 ::before ::after | 记录自己的前端学习日子