笔记练习:《Javascript入门经典(第5版)》page185_15.10_Practice

来源:互联网 发布:装修论坛 淘宝 编辑:程序博客网 时间:2024/05/01 00:47

5.2 的代码,让目标图像在垂直和水平方向都晃动,而不是简单地从左移到右。同时,要把 Javascript 和 CSS 提取到外部文件。

尝试修改代码,添加第二个目标图像,使其具有不同的运动模式。


代码内容如下:

HTML文件

!DOCTYPE html><html><head lang="en">    <meta charset="UTF-8">    <title>Space Shooter</title>    <link rel="stylesheet" href="myCSS.cs" type="text/css" />    <script src="myJS.js"></script></head><body>    <div id="range">        <div id="score"></div>        <img src="ufo.png" alt="Fire!" id="img1">        <img src="monster.png" alt="Fire!" id="img2">    </div></body></html>

JS 文件

var shots = 0;//射击次数var scoreE = 0;//UFO得分计数var scoreM = 0;//怪兽得分计数var timer1 = null;//计时器var el = null;var ml = null;function moveIt(){    //是图片活动    if(parseFloat(el.style.left)>(screen.width - 400))el.style.left = 0;    el.style.left = parseInt(el.style.left) + 6 + 'px';    el.style.top = 100 +(80 * Math.sin(parseInt(el.style.left)/30)) + 'px';    if(parseFloat(ml.style.left)>(screen.width - 400))ml.style.left = 0;    ml.style.left = parseInt(ml.style.left) + 6 + 'px';    ml.style.top = 80 +(80 * Math.cos(parseInt(ml.style.left)/80)) + 'px';    timer1 = setTimeout(moveIt,40);}function scoreEUp(){    scoreE++;}function scoreMUp(){    scoreM++;}function scoreBoard(){    document.getElementById("score").innerHTML = " 射击:" + shots + " UFO得分:" + scoreE + " 怪兽得分:" + scoreM;}window.onload = function(){    el = document.getElementById("img1");    el.onclick = scoreEUp;    ml = document.getElementById("img2");    ml.onclick = scoreMUp;    document.getElementById("range").onclick = function(){        shots++;        scoreBoard();    }    scoreBoard();    el.style.left = '50px';    ml.style.left = '50px';    moveIt();}


CSS 文件

#range {    position: absolute;    top: 0px;    left: 0px;    background: url(space.jpg);    cursor:crosshair;    width: 100%;    height: 300px;}#img1 {    position: absolute;    border: none;    left:0px;    top:100px;    padding: 10px;    width: 80px;    height: 80px;}#img2 {    position: absolute;    border: none;    left:0px;    top:100px;    padding: 10px;    width: 100px;    height: 70px;}#score {    font: 16px normal arial,verdana,sans-serif;    color: white;    padding: 10px;}



案例中提供涉及用到的图片素材:

图1 ufo.png



图2 monster.png



图3 space.jpg



图4  实现效果

0 0
原创粉丝点击