简体   繁体   中英

jQuery animation infinite doesn't work

I've got this code

var goRight = function() {
  $(this).animate({'left:' '40px'}, 1000, goLeft);
};

var goLeft = function() {
  $(this).animate({'left:' '-40px'}, 1000, goRight);
};

var main = function() {
  $('.square').hover(function() {
    $(this).toggleClass('active');
  });
$('.square').goRight();
};

$(document).ready(main);

It supposed to move the square(a div) to the right then back to the left infinitely and make it blue when the user hovers over it. But it doesn't work. The problem is probably in the goRight and goLeft , functions. Since if I remove them completely the hover changes the color fine. And when these functions are there nothing works.

You need to do the chaining like this

 $.fn.goRight = function() { this.animate({ 'left': '40px' }, 1000, function() { $(this).goLeft() }); return this; }; $.fn.goLeft = function() { this.animate({ 'left': '-40px' }, 1000, function() { $(this).goRight() }); return this; }; var main = function() { $('.square').hover(function() { $(this).toggleClass('active'); }); $('.square').goRight(); }; $(document).ready(main); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div style="width:100px;height:100px;background:black;position:relative;" class="square"></div> 

For more about jQuery plugin development : https://learn.jquery.com/plugins/basic-plugin-creation/

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