概述:通过获取鼠标距离页面的左边距和上边距,来动态设置图片的left和top值。
html部分
<img src="./img/qqhf-16.jpg" width="60" alt="">
css部分
<style>
img{
position:absolute; //设置图片绝对定位
}
</style>
js部分
<script>
// 获取图片元素
var mousImg = document.querySelector("img");
// 绑定鼠标移动事件
document.onmousemove = function(e) {
var e = e || window.event; //兼容浏览器 IE8以下(包含IE8)不支持e只支持window.event
var x = e.pageX; //获取鼠标距离页面左边距
var y = e.pageY; //获取鼠标距离页面上边距
mousImg.style.left = x - (mousImg.width)/2 + "px"; //使鼠标的位置在图片中间
mousImg.style.top = y - (mousImg.height)/2 + "px";
}
</script>