代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<style>
* {
margin: 0;
padding: 0;
}
html,
body {
width: 100%;
height: 100%;
}
div {
width: 100%;
height: 100%;
background-color: aqua;
cursor: url("image/pai.jpg"), auto;
}
.cangying {
position: fixed;
width: 100px;
height: 100px;
z-index: 10;
}
p {
position: fixed;
top: 0;
right: 0;
font-size: 30px;
font-weight: 600;
}
</style>
<body>
<div>
<img src="image/cangying.jpg" class="cangying" />
<p></p>
</div>
</body>
<script>
// 次数
var count = 0;
// 苍蝇随机出现
var cangying = document.querySelector(".cangying");
var p = document.querySelector("p");
// 苍蝇被点击换位置
cangying.addEventListener("click", function (e) {
// 获取屏幕可视区域的宽高
var w = document.documentElement.clientWidth;
var h = document.documentElement.clientHeight;
// 得到一个两数之间的随机整数(包括两个数在内)
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; //含最大值,含最小值
}
// w 和 h 减去100px,就是苍蝇的宽高,因为定位的时候那啥,你懂的
var width = getRandomIntInclusive(1, w - 100);
var height = getRandomIntInclusive(1, h - 100);
this.style.left = width + "px";
this.style.top = height + "px";
// 次数++
count++;
p.innerHTML = "拍死" + count + "只苍蝇了!";
});
</script>
</html>
效果
资源
cangying.jpg
pai.jpg