鼠标点击页面某处的时候可以让小精灵移动到该处
css代码:
<style>
html,
body {
height: 100%;
width: 100%;
background-color: black;
/* 根据图片的背景色调整页面背景色 */
overflow: hidden;
}
img {
width: 100px;
/* border: 1px solid red; */
/* 定位 */
position: absolute;
}
</style>
html代码:
<img src="./images/girl.gif" alt="" />
script代码
var oImg = document.querySelector("img");
//在整个文档里移动
//获取元素的自身宽度
// oImg.offsetWidth
//oImg.offsetHeight
document.onmousemove = function (e) {
oImg.style.left = e.pageX - oImg.offsetWidth / 2 + "px";
oImg.style.top = e.pageY - oImg.offsetHeight / 2 + "px";
};
//鼠标点击
document.onclick = function (e) {
oImg.style.left = e.pageX - oImg.offsetWidth / 2 + "px";
oImg.style.top = e.pageY - oImg.offsetHeight / 2 + "px";
};
小精灵图片: