jQuery animate() and CSS calc()

╄→尐↘猪︶ㄣ 提交于 2019-12-04 22:53:37

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
});

I was Googling for the answer to this exact question. I saw this link and was like "YES!" Then I saw the answers and was like "no!" Here's what I did, based on your example:

var nextHeight = $element.parent().width()-30;
$element.animate({
    height:nextHeight
}, {duration:500, complete:function(){ $element.width("calc(100% - 30px)"); } });

I know I didn't do EXACTLY what you asked, but it animates to where you want it to animate to and when you finish it's the width you wanted it to be set to. As long as you're not resizing WHILE it's animating, I think it's a decent workaround.

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