简体   繁体   中英

Javascript ID reassignment

I am working on a project, and I want to make 4 images move in a circular fashion once I click on one of them. This is what I have so far, but I can't figure out how to make the circle keep going. Any help?

<!DOCTYPE html>
<html>
<head>
<title> Lab 13B </title>
<style>
    #pic1 {
        padding-left:325px;
    }
    #pic2 {
        padding-top: 100px;
    }
    #pic3 {
        padding-left: 350px;
        padding-top: 100px;
    }
    #pic4 {
        padding-left: 325px;
        padding-top: 120px;
    }
</style>
<script>
    function one() {
        document.getElementById("pic1").src = "water.PNG";
        document.getElementById("pic2").src = "fire.PNG";
        document.getElementById("pic3").src = "Air.PNG";
        document.getElementById("pic4").src = "earth.PNG";
        document.getElementById("pic1").id = "pic2";
        document.getElementById("pic2").id = "pic4";
        document.getElementById("pic3").id = "pic1";
        document.getElementById("pic4").id = "pic3";
    }
</script>
</head>
<body>
    <img src = "Air.PNG" alt="air" width="300px" height="300px" id="pic1" onclick="one()";> <br>
    <img src = "water.PNG" alt="water" width="300px" height="300px" id="pic2" onclick="one()";> 
    <img src = "earth.PNG" alt="earth" width="300px" height="300px" id='pic3' onclick="one()";> <br>
    <img src = "fire.PNG" alt="fire" width="300px" height="300px" id='pic4' onclick="one()";> 
</body>
</html>

You are essentially talking about an animation where you need to change something around after specific time interval.

To achieve things like that Javascript provides setInterval function where you can run a piece of code responsible for "change" after given interval in milliseconds. So your function one will look something like

function one() {
  setInterval(function() {
    // your logic for swapping src of images
  }, 1000)
}

But this will require you to properly handle click event, first click will start the animation but second will create the interval again and so on, so considering this if you already have interval running then on second click you might want to stop the animation or at least prevent the creation of second interval. This might be of some help Is there any way to kill a setInterval loop through an Onclick button

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