用javascript制作一个圆圈弹跳

时间:2016-10-06 16:00:06

标签: javascript

我的目标是让一个圆圈向右移动,直到它到达窗口的末端。然后它应向左转,直到它撞到窗口的左侧。我正在努力弄清楚为什么我的圆圈在撞到窗户右侧时不会反弹的原因。在'弹跳'之前圆圈没有达到整个窗口宽度。

这是html部分:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Animate</title>
    <script src="animate.js"></script>
</head>
<body>
    <h2>JavaScript Timers</h2>
    <p>
        <button onclick="left('thingToMove');">&larr; Move Left</button>
        <button onclick="stopMoving();">Stop</button>
        <button onclick="right('thingToMove');">Move Right&rarr;</button>
    </p>
    <div id='thingToMove' style="left:10px; position:absolute;">
        <img src="bluecircle.png" >
    </div>
    <div id="instructions" style="position: relative; top:1.25in;">
        <h3>Instructions</h3>
        <ol>
            <li>Re-write animate.js to use <code>setInterval()</code> instead of <code>setTimeout</code></li>
            <li>Add functionality to "bounce" off the side of the window rather than disappear.<br /><em>hint:</em> <code>window.innerWidth</code></li>
        </ol>
    </div>
</body>
</html>

这是我到目前为止我的javascript。

var moving = "";
function $(id){
    return document.getElementById(id);
}
function right(id){
        stopMoving();
        $(id).style.left = parseInt($(id).style.left) + 1 + 'px';
        moving = setInterval(function(){right(id);},10);
        alert(window.innerWidth);
        if($(id).style.left > (window.innerWidth) + 'px'){
            left(id);
        }
}

function left(id){ 
        stopMoving();
        $(id).style.left = parseInt($(id).style.left) - 1 + 'px';
        moving = setInterval(function(){left(id);},10);
        if($(id).style.left < 0 + 'px'){
            right(id);
        }
}

function stopMoving(){
        window.clearInterval(moving);
}

在向左反弹之前,圆圈通常会向右移动约90px。我不知道为什么。

1 个答案:

答案 0 :(得分:3)

您正在比较这些宽度的字符串,这意味着字符串比较规则适用:Thursday, October 6, 2016 - 5:38:09 PM Failure sending mail. at System.Net.Mail.SmtpClient.Send(MailMessage message) at com.progamma.IDMailer.SendMail() DTT_LEVEL=5 DTT_MSGLEVEL=3 DTT_LEVEL=5 DTT_MSGLEVEL=3 Failure sending mail. at System.Net.Mail.SmtpClient.Send(MailMessage message) at com.progamma.IDMailer.SendMail() The message could not be sent to the SMTP server. The transport error code was 0x80040217. The server response was not available at System.Web.Mail.SmtpMail.LateBoundAccessHelper.CallMethod(Object obj, String methodName, Object[] args) at System.Web.Mail.SmtpMail.CdoSysHelper.Send(MailMessage message) at System.Web.Mail.SmtpMail.Send(MailMessage message) at com.progamma.IDMailer.SendMailSSL() -------------------------------------------------------------------- Thursday, October 6, 2016 - 5:38:25 PM Failure sending mail. at System.Net.Mail.SmtpClient.Send(MailMessage message) at com.progamma.IDMailer.SendMail() TRUE ,因为'90px' > '100px'大于9

字符串比较规则不是&#34;人类比较&#34;规则。