| <!DOCTYPE html>
|
| <html lang="en">
|
|
|
| <head>
|
| <meta charset="UTF-8">
|
| <meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| <title>Document</title>
|
| <style>
|
| * {
|
| margin: 0;
|
| padding: 0;
|
| }
|
|
|
| body {
|
| background-color: #ccc;
|
| }
|
|
|
| #range {
|
| position: absolute;
|
| left: 0;
|
| top: 0;
|
| background: url(space.jpg);
|
| background-size: cover;
|
| cursor: crosshair;
|
| width: 100%;
|
| height: 300px;
|
| }
|
|
|
| #img1 {
|
| position: absolute;
|
| border: none;
|
| left: 0;
|
| top: 100px;
|
| padding: 10px;
|
| }
|
|
|
| #score {
|
| color: white;
|
| padding: 10px;
|
| }
|
| </style>
|
| </head>
|
|
|
| <body>
|
| <div id="range">
|
| <div id="score"></div>
|
| <img src="ufo.png" alt="" id="img1">
|
| </div>
|
| <script>
|
| var timer = null;
|
| var el = null;
|
| var score = 0; // 得分:射中的次数
|
| var shots = 0; // 总的射击数
|
| function moveIt() {
|
|
|
| // 在元素到达屏幕最右侧时把它重新移动到屏幕最左侧
|
| if (parseInt(el.style.left) > (screen.width - 50)) {
|
| el.style.left = 0;
|
| }
|
|
|
| // 每次把指定元素向右移动6个像素
|
| el.style.left = parseInt(el.style.left) + 6 + 'px';
|
|
|
| // 垂直方向的变化,top属性值从 100-80= 20(px) 变化到 100+80 = 180(px)
|
| el.style.top = 100 + (80 * Math.sin(parseInt(el.style.left) / 50)) + "px"
|
|
|
| // 利用setTimeout()每隔25毫秒调用自己一次
|
| timer = setTimeout(moveIt, 25)
|
| }
|
|
|
| function scoreUp() {
|
| score++;
|
| }
|
|
|
| function scoreboard() {
|
| document.querySelector("#score").innerHTML = "Shots:" + shots + " Score:" + score;
|
| }
|
| window.onload = function () {
|
| el = document.querySelector("#img1")
|
|
|
| // 当动画元素(ufo图片)上检测到鼠标点击时,就会调用函数scoreUp(),增加用户得分。
|
| el.onclick = scoreUp;
|
|
|
| // 通过鼠标点击实现射击,在range范围内,鼠标指针会变成十字符号
|
| document.querySelector("#range").onclick = function () {
|
| shots++;
|
| scoreboard();
|
| }
|
| scoreboard()
|
| el.style.left = "50px"
|
| moveIt();
|
| }
|
| </script>
|
| </body>
|
|
|
| </html> |