console
var oDiv = document.getElementById('demo')
function getStyle(ele,attr){
if(window.getComputedStyle){
return getComputedStyle(ele,null)[attr]
}else{
return ele.getCurrentStyle[attr]
}
}
oDiv.onmouseover = function(e){
var disX = parseInt(getStyle(this,'width')) / 2
var disY = parseInt(getStyle(this,'height')) / 2
console.log(this.style.width)
document.onmousemove = function(e){
var st = document.body.scrollTop || document.documentElement.scrollTop
var sl = document.body.scrollLeft || document.documentElement.scrollLeft
var x = e.clientX
var y = e.clientY
oDiv.style.left = x + sl - disX + 'px'
oDiv.style.top = y + st - disY + 'px'
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>div随鼠标移动</title>
</head>
<body>
<div style="height:1000px">
<div class="demo" id="demo"></div>
</div>
</body>
</html>
.demo{
position:absolute;
left:0;
top:0;
width:150px;
height:150px;
background: #f40;
}