简体   繁体   中英

How to tweak jQuery animation for the element to stay in the middle?

I have a jQuery Mobile page and I want to animate the Save button on this page to lose half of its width/height and then to animate back to its original size.

function animateMe() {    
  var originalHeight = $("#btnSave").height();
  var originalWidth = $("#btnSave").width();
  $("#btnSave").animate(
    {"height": originalHeight / 2, "width": originalWidth / 2}, 
    { duration: "fast" }
  );            

  $("#btnSave").animate(
    {"height": originalHeight, "width": originalWidth}, 
    { duration: "fast" }
  );                  
}

The animation works fine, but I was hoping for the button to collapse its middle, instead it collapses to its top/left location (as one would expect).

How can I animate the button to collapse to its middle and then back?

This would be much better using CSS3 animation and the scale transform, instead of relying on jQuery's animate . Beside other advantages with using CSS3 animations for this, the performance should be much better.

Here's a rough example, just to give you an idea: http://jsfiddle.net/ghinda/8nNeS/

You would have to add to the animation a position change, or padding change, that offsets the element's image as well.

$("#btnSave").animate({
  "height": originalHeight / 2 + "px",
  "width": originalWidth / 2 + "px",
  "padding-left": (originalWidth / 2) + "px",
  "padding-top":  (originalHeight / 2) + "px",
}, {
  duration: "fast"
});

Something similar to that, anyway.

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