jQuery animate() and CSS calc()

前端 未结 2 941
梦毁少年i
梦毁少年i 2020-12-18 21:29

I tried to set CSS calc() using jQuery animate, for example:

$element.animate({
    height: \'calc(100% - 30px)\'
}, 500);

and

2条回答
  •  独厮守ぢ
    2020-12-18 22:15

    Setting calc() like you want won't work. The easiest way to do it is to "calculate" it's value into a variable, something like this:

    var newHeight = $('.container').height() - 30;
    

    then you can use the animate() with the new variable, something like this:

    $('.animate-me').animate({
      height: newHeight
    }, 500);
    

    I have created a CodePen with an example. When you click the lighter square ( .animate-me ) it will get animated to 100% of the .container's height minus 30px. I hope this is what you were looking for...

    http://codepen.io/anon/pen/JYqPxm

    If you want it to work also on window resize and you are using global variables, then you can just update the variables from inside a resize function, like so:

    $(window).on("resize",function() {
      // update all variables that you need
    });
    

提交回复
热议问题