<style>
.a{width: 100px;height: 100px;background-color: #000;position: absolute;}
</style>
<div class="a"></div>
<script>
var a = document.querySelector('.a');
document.addEventListener('mousemove',function(e){
var maxWidth = document.documentElement.clientWidth - a.offsetWidth;
var maxHeight = document.documentElement.clientHeight - a.offsetHeight;
console.log(maxWidth,maxHeight)
var x = e.pageX - a.offsetWidth / 2;
var y = e.pageY - a.offsetHeight / 2;
if(x < 0){
x = 0
}
if(y < 0){
y = 0
}
if(x > maxWidth){
x = maxWidth;
console.log(e.pageX)
}
if(y > maxHeight){
y = maxHeight;
}
a.style.left = x + 'px';
a.style.top = y + 'px';
})
</script>