<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#div{
height: 200px;
width: 200px;
background-color: #f00;
position: absolute;
}
</style>
</head>
<body style="height: 2000px;">
<div id="div"></div>
<script>
// 把 scrollTop和scrollLeft封装成一个函数 已josn的形式返回出去,
function getPos(ev){
var scrollTop = document.documentElement.scrollTop||document.body.scrollTop;
var scrollLeft = document.documentElement.scrollLeft||document.body.scrollLeft;
return {x: ev.clientX+scrollLeft, y:ev.clientY+scrollTop};
};
document.onmousemove = function(ev){
// event它是一个内置对象
var oEvent = ev||event;
var div = document.getElementById('div');
// 当我们需要用到scrollTop和scrollLeft的时候,只需要调用getPos
var pos = getPos(oEvent);
div.style.left = pos.x+'px';
div.style.top = pos.y+'px';
};
</script>
</body>
</html>
鼠标贪吃蛇效果
最新推荐文章于 2021-12-22 00:43:57 发布