简体   繁体   中英

Function to move an image when image is clicked?

I have an html file called index.html, and it has this div in there

  <body>
     <div id="rock"> <img src="rock.PNG" alt="rock" onclick="test()"> </div>
     <div id="paper"> <img src="paper.PNG" alt="rock"></div>
     <div id="scissors"> <img src="scissors.PNG" alt="rock">  </div>

test is my function, and its within the same file and its written here

 <script type="text/javascript">
    function test(){
      var elem = document.getElementById("rock");
      var pos = 0;
      var id = setInterval(frame, 10);
      function frame() {
        if (pos == 350) {
          clearInterval(id);
        } else {
          pos++;
          elem.style.top = pos + 'px';
          elem.style.left = pos + 'px';
        }
      }
    }
  </script>

but when my page runs I click the image, and it does not move. the image is displayed, and the onclick does work (i tested it with alert) but the image won't move... any ideas?

You need to specify the position attribute, likely relative . You could also use absolute or fixed positioning if one of those fits your needs better.

#rock, #paper, #scissors {
    position: relative;
}

Have you tried change the position of the elements?

https://www.w3schools.com/css/css_positioning.asp

Ex:

<body>
    <div id="rock" onclick="test()" style="position:absolute;"> <img src="teste.PNG" alt="rock" > </div>
</body>
<script type="text/javascript">
    var pos = 0;
    var elem = null;
    var id = null;
    function test() {
        console.log("test");
        elem = document.getElementById("rock");
        id = setInterval(frame, 10);
    }

    function frame() {
        console.log("frame");
        if (pos == 350) {
            clearInterval(id);
        } else {
            pos++;
            elem.style.top = pos + 'px';
            elem.style.left = pos + 'px';
        }
    }
</script>

You need a relative position to be able to change top , bottom , left , right properties

<div id="rock" style="position: relative;"> 
   <img src="rock.PNG" alt="rock" onclick="test()"> 
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM