简体   繁体   English

如何使两个相同的类对相同的 javascript function 以不同的方式工作?

[英]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.我想用相同的 javascript function 使这两个圆圈移动不同(它们在移动时获得相同的方向),但我是使用 javascript 的新手并且不知道如何制作它。

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.我不知道如何使 javascript 在 html 中的相同类之间有所不同以获得相同的 function 但根据其特定的 class 的不同工作方式不同。我的理想代码将使两个圆圈随机移动,但在独立的方向上从一个圆圈移动到另一个圆圈。

<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

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

To target circle bb :circle bb为目标:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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