Correcting teacher:WJ
Correction status:qualified
Teacher's comments:总得来说写的不错,下次记得每天的作业写在一起!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>元素的offset的位置与大小</title>
<style>
.box {
width: 120px;
height: 120px;
position: absolute;
top: 50px;
left: 10px;
}
.box img {
width: 100%;
}
</style>
</head>
<body>
<div class="box"><img src="images/4.jpg" /></div>
<button>快跑</button>
<button>站住</button>
</body>
<script>
const thief = document.querySelector(".box");
const btn1 = document.querySelector("button:first-of-type");
const btn2 = document.querySelector("button:last-of-type");
//添加事件
btn1.addEventListener("click", start, { once: true });
btn2.addEventListener("click", stop);
//定时器
let timer = null;
function start() {
console.log(thief.offsetLeft);
timer = setInterval(function () {
thief.style.left = thief.offsetLeft + 10 + "px";
thief.style.top = thief.offsetTop + 10 + "px";
}, 200);
}
function stop() {
clearInterval(timer);
}
</script>
</html>