jQuery Animate Padding to Zero

2019-02-16 08:52发布

I have the following snippet that toggles padding when hovering (see example here):

<div id="outer"><div id="inner"></div></div> 
<script> 
  $("#inner").mouseenter(function () {
    $("#outer").animate({ 'padding' : '20px' }, "slow");
  });
  $("#inner").mouseleave(function () {
    $("#outer").animate({ 'padding' : '0px' }, "slow");
  });
</script>

The goal is to have the padding animate both in and out, however currently no animation appears for animating out. I did some tests, and if I change the leave padding to 10 pixels (from 0 pixels) it runs an animation, but starts at zero and animates outwards. I'm running jQuery 1.4.3. Any way to fix this?

4条回答
Fickle 薄情
2楼-- · 2019-02-16 09:22

Looks like a bug in 1.4.3 (rewritten css part). 1.4.2 works fine:

http://www.jsfiddle.net/YjC6y/44/

I will investigate it further and update this post.

查看更多
在下西门庆
3楼-- · 2019-02-16 09:23

I just realized jquery is not reacting very well to hyphens "-" within animation but you get the same result by getting ride of the hyphen and capitalizing the first letter after. So for you will have something like this:

    $("#inner").mouseleave(function () {
       $("#outer").animate({
     paddingTop : 0,
         paddingRight : 0,
         paddingBottom : 0,
         paddingLeft : 0,
         borderLeftWidth: 0,
         borderTopWidth: 0,
         borderRightWidth: 0,
         borderBottomWidth: 0,

 }, slow);
查看更多
何必那么认真
4楼-- · 2019-02-16 09:37

Another solution would be to use a cssHook. Brandon Aarons jquery-cssHooks come to mind (in this case the padding hook in marginpadding.js)

You can test it here

查看更多
趁早两清
5楼-- · 2019-02-16 09:42

Definitely an animation bug in 1.4.3, for now you can work-around by animating the individual properties like this:

$("#inner").mouseleave(function () {
  $("#outer").animate({ 
    'padding-top' : 0,
    'padding-right' : 0,
    'padding-bottom' : 0,
    'padding-left' : 0,
  }, "slow");
});

You can test it out here.

查看更多
登录 后发表回答