if语句在函数内部不起作用

时间:2017-10-08 20:22:46

标签: javascript function if-statement

我希望我的图片一步一步向左移动到1300px并使用jobbra按钮,所以我添加了一个if语句来实现这一点,但这对onlclick不起作用。如果我删除if语句按钮单击功能单独工作。我的if语句有什么问题?谢谢

 <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>PingPongKép</title>
        <link rel="stylesheet" href="CSS/style.css">
    </head>

    <body>

        <div id="ilonakep">
            <img src="/img/ilona.jpg" alt="ilona">
        </div>

        <p id="gombok">

            <button onclick="balra()">Balra</button>

            <button onclick="jobbra()">Jobbra</button>



        </p>

        <script>
            var jobbAnim = 1;
            var speed = 1;
            var balAnim = 0;



            function jobbra() {

          if ( jobbAnim < 1300){
              var jobbAnim = jobbAnim + speed;
          }
            document.getElementById("ilonakep").style.marginLeft = jobbAnim + "px";

           }



            function balra() {
            document.getElementById("ilonakep").style.marginLeft = balAnim + "px";

            }
        </script>







</body>
</html>

1 个答案:

答案 0 :(得分:0)

希望这能解决问题

&#13;
&#13;
var jobbAnim = 1;
var speed = 10;
var balAnim = 0;
var max = 80; // 1300 here.
function jobbra () {
    var ilonakep = document.getElementById("ilonakep");
    if (ilonakep.clientWidth + parseInt(ilonakep.style.marginLeft) < max || ilonakep.style.marginLeft == '') {
        jobbAnim = jobbAnim + speed;
        ilonakep.style.marginLeft = jobbAnim + "px";
    } else console.log(max+' reached');
}
function balra () {
    document.getElementById("ilonakep").style.marginLeft = balAnim + "px";
    jobbAnim = 0;
}
&#13;
#ilonakep {
  width: 50px;
  height: 50px;
  border: 1px solid #000;
  margin: 0;
}
&#13;
<div id="ilonakep">
    <img src="/img/ilona.jpg" alt="ilona">
</div>
<p id="gombok">
    <button onclick="balra()">Balra</button>
    <button onclick="jobbra()">Jobbra</button>
</p>
&#13;
&#13;
&#13;