简体   繁体   中英

How do I make two identical classes work differently with the same javascript function?

I want to make these two circles move differently (they acquire the same direction while moving) with the same javascript function, but I am quite new using javascript and do not know how to make it.

I do not know how to make javascript differ between the same classes in html to get the same function but work differently depending on their specific class. My ideal code would make the two circles move randomly but in independent direction from one to another.

<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="css/stylesheet.css">
    <script type="text/javascript" src="https://code.jquery.com/jquery-1.7.1.min.js"></script>
</head>
    
<body>
    <div class="wrapper" style="top:18%;left:15%">
        <a href="childs_html/aa.html" class="circle aa">aa</a>
    </div>
    <div class="wrapper" style="top:58%;left:18%">
        <a href="childs_html/bb.html" class="circle bb">bb</a>
    </div>
    <script src="javascript/circle_movement.js"></script>
</body>
body {
    overflow: hidden;
    margin: auto;
    width: 640px; 
    padding: 50px;    
  }

  .wrapper {
    position:absolute;
    height:200px; width:200px;
    /* border-style:solid; */
  }
  
  .circle {
    position:relative;
    height:100px; width:100px;
    margin-top:50px;margin-left:50px;
    border-radius:50%;
    border-style:solid;
  }

$(document).ready(function(){
    animation();
}

function randomNumber(min, max) { 
    return Math.floor(Math.random() * (max - min) + min);
} 

function new_position() {
    var newt = randomNumber(-50,50);
    var newl = randomNumber(-50,50);

    return [newt, newl]
}

function animation(){
    var newpos = new_position();
    var speed = 2000;

    $('.circle').animate({ top: newpos[0], left: newpos[1] }, speed, function(){
        animation();        
      });

};

Thank you very much!

To target circle aa :

$('.circle.aa').animate({ top: newpos[0], left: newpos[1] }, speed, function(){
     // Animation for circle aa  
     animation_aa();      
});

To target circle bb :

$('.circle.bb').animate({ top: newpos[0], left: newpos[1] }, speed, function(){
     // Animation for circle bb 
     animation_bb();      
});

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