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