随鼠标移动事件

DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<meta http-equiv="X-UA-Compatible" content="ie=edge">

<title>Documenttitle>

<style>

div{

width:100px;

height:100px;

background-color: red;

position:absolute;

left:0;

top:0;

}

</style>

head>

<body style="height: 2000px">

<div >div>

<script>

function getPosition(ev){

var oEve=window.event||ev;

var scrollLeft=document.documentElement.scrollLeft||document.body.scrollLeft;

//scrollLeft文档距离可视区clientX的距离 滚动条的距离

//eve.clientX 鼠标在可视区中的坐标

var scrollTop=document.documentElement.scrollTop||document.body.scrollTop;

var posX=oEve.clientX+scrollLeft;

//鼠标在整个文档中的坐标即就是包括滚动过后的区域(可是区与页面顶部的距离):页面中的绝对位置

var posY=oEve.clientY+scrollTop;

return{x:posX,y:posY};

}

document.onmousemove=function(ev){

var oDiv=document.getElementsByTagName('div')[0];

var position=getPosition(ev);

oDiv.style.left=position.x+'px';

oDiv.style.top=position.y+'px';

}

</script>

body>

html>

你可能感兴趣的:(前端)