문제

So I need help, I need to create a javascript file (with matching HTML), that allows an image to move from left to right continuously. And then when the user clicks the mouse button, the image must then move up and down continuously.

I so far I have tried to do the first part, however using a code I have found that it does not work for me and I'm not too sure why. I feel like I'm missing something so obvious but I can't figure it out.

Thanks in advance.

This is my code

HTML:

<html>
<head>
<title>Task 2</title>
<link rel="stylesheet" type="text/css" href="task2.css">
<script src="task2.js"></script>

<div id="animate">Sample</div>
</head>
</html>

CSS:

#animate {
    position: relative;
    border: 1px solid green;
    background: yellow;
    width: 100px;
    height: 100px;
}

JavaScript:

(document).ready(function() {
    var width = (document).width();

    function goRight() {
        ("#animate").animate({
        left: width
      }, 5000, function() {
         setTimeout(goLeft, 50);
      });
    }
    function goLeft() {
        ("#animate").animate({
        left: 0
      }, 5000, function() {
         setTimeout(goRight, 50);
      });
    }

    setTimeout(goRight, 50);
});
도움이 되었습니까?

해결책

Add a handler on click on image and funcs to updown:

    function goUp() {
    $("#animate").animate({
    top: 0
  }, 5000, function() {
     setTimeout(goDown, 50);
  });
}
function goDown() {
    $("#animate").animate({
    top: height
  }, 5000, function() {
     setTimeout(goUp, 50);
  });
}
$("#animate").on('click',function(){$('#animate').stop();
              if(upleft == 0)
              {goDown(); upleft=1;}
                                else {goLeft();upleft=0}
})

FIDDLEEXAMPLE

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top