jQuery bind unbind animation

本秂侑毒 提交于 2020-01-06 15:33:12

问题


I made this piece of code,i'm trying to animate a block of text/div back and forward, but why this works only the first time for the "placeRight" function? Is there something wrong with the right : "+=750" attribute?

$(document).ready( function ( ) {
   $("#text").click(placeRight);
});   

    var placeRight = function() {     
      $("#text").animate( { right :  "+=750" }, 1300); 
      $("#text").unbind("click"); 
      $("#text").click(placeLeft);
    }

    var placeLeft = function() {     
      $("#text").animate( { left :  "+=750" }, 1300); 
      $("#text").unbind("click");
      $("#text").click(placeRight);
    }

回答1:


Yeah, you have double time $("#text").animate( { left : "+=750" }, 1300);
so you're trying to place it always to +750px position

change it like this

$(document).ready( function ( ) {
   $("#text").click(placeRight);
});   

var placeRight = function() {     
  $("#text").animate( { right :  "+=750" }, 1300);
  $("#text").unbind("click"); 
  $("#text").click(placeLeft);
}

var placeLeft = function() {     
  $("#text").animate( { left :  "-=750" }, 1300); //or { right: 0 }
  $("#text").unbind("click");
  $("#text").click(placeRight);
}



回答2:


You could do it with less code. Here's a working demo: http://jsfiddle.net/kkZtD/1/




回答3:


try this:

$(document).ready(function(){
   $("#text").click(function(){
      $(this).animate({ right: "+=750" }, 1300).animate({ left: "0" }, 1300);
   });
});


来源:https://stackoverflow.com/questions/7378405/jquery-bind-unbind-animation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!