简体   繁体   中英

How can I animate a calculated position with JQuery

So I have a variable with a calculated position that centers the element with JQuery, reason I did this is because I will not know the width of the element so I made it dynamic like so.

var $x = $("#line").outerWidth();

var $result = "calc( 50% - " + $x +"px / 2 )";

Then I tried to animate it to the center (value of $result) like so:

   $("#line").animate({ 
        "left": $result,
        "top" : "15px"

    }, 1000 );

Sadly this did not work, only the top value moved.

Any advice is greatly appreciated, thank you.

jsBin demo

If you already use calc (CSS3) than you'll have nothing against using in your CSS:

Using CSS3 transition and calc()

#line{
    transition: 1s;
    /*...other stuff...*/
}

and in your jQuery (instead of .animate() )

var outW2 = $("#line").outerWidth() / 2;

$("#line").css({ 
  left : "calc(50% - "+ outW2 +"px)",
  top  : 70
});

Using .animate() and negative margin (for centering)

For all older browsers , you can simply use .animate() as you did ,
moving the element to 50% but also to a - half-width left margin (to center it):

var outW2 = $("#line").outerWidth() / 2;

$("#line").animate(){
  left: "50%",
  marginLeft : -outW2
}, 1000);

jsBin demo (crossbrowser solution)

jQuery's animate won't accept the css3 calc as a valid pixel value. You'll need to first calculate what 50% is.

var containerWidth = $("#line").parent().outerWidth();

Then use that in your $result .

var $result = containerWidth * 0.5 - $x * 0.5;

This should give you the horizontal pixel location to animate it to.

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