博客列表 >元素的offset的位置与大小

元素的offset的位置与大小

霏梦
霏梦原创
2020年06月19日 13:00:181041浏览

- 作者:霏梦

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6. <title>元素的offset的位置与大小</title>
  7. <style>
  8. .box {
  9. width: 120px;
  10. height: 120px;
  11. position: absolute;
  12. top: 50px;
  13. left: 10px;
  14. }
  15. .box img {
  16. width: 100%;
  17. }
  18. </style>
  19. </head>
  20. <body>
  21. <div class="box"><img src="images/4.jpg" /></div>
  22. <button>快跑</button>
  23. <button>站住</button>
  24. </body>
  25. <script>
  26. const thief = document.querySelector(".box");
  27. const btn1 = document.querySelector("button:first-of-type");
  28. const btn2 = document.querySelector("button:last-of-type");
  29. //添加事件
  30. btn1.addEventListener("click", start, { once: true });
  31. btn2.addEventListener("click", stop);
  32. //定时器
  33. let timer = null;
  34. function start() {
  35. console.log(thief.offsetLeft);
  36. timer = setInterval(function () {
  37. thief.style.left = thief.offsetLeft + 10 + "px";
  38. thief.style.top = thief.offsetTop + 10 + "px";
  39. }, 200);
  40. }
  41. function stop() {
  42. clearInterval(timer);
  43. }
  44. </script>
  45. </html>
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议