简体   繁体   中英

Animate a display inline to block change

I am trying to create a sticky header which changes size when the page is scrolled. One of the main features I want to implement is that an image in the header shrinks down and moves to the left.

So far I have the shrinking down working nicely all animated. I also have the moving to the left working, but its not animated.

In jQuery I am calling

$('#page_header_logo_img').css({
    "padding-left":"20%",
    "display":"inline"
})

at one point and then later call

$('#page_header_logo_img').css({
    "padding-left":"0",
    "display":"block"
})

Which works beautifully for moving it to exactly where I want... only problem is it jumps there.

I have tried incorporating the jQuery Animate effect but couldn't get it to work.

Here is a JSFiddle of what I currently have All I need is for the movement left and right to be smooth and not instant.

EDIT FOR ANSWER

I accepted the answer that got me closest, and also answered the question I asked. However it didn't quite get me what I wanted, so thought I would post the final solution here.

I changed the image to be position: absolute; and then dynamically set the margin and the left property.

You can see a working JSFiddle here

You can consider using CSS transitions.

Adding transition: padding-left 0.3s ease-in-out; to the styles of #page_header_logo_img gives it an animated transition when moving left.

See here in your JSFiddle. It is not very polished but you can see how the CSS transition can be used.

See this for more information of CSS transitions.

if you want animation effect you can use .animate() instead of .css() but you can use display in it because display will not work in .animate() .

Rest the function would be like this

var scrolPos = $(window).scrollTop();
if(scrolPos>100){
  $('#page_header_logo_img').animate({
    paddingLeft:"20%"
  });
} else {
  $('#page_header_logo_img').animate({
    paddingLeft:"0"
  });
};

You are just changing the CSS properties and so there is an jump.

Use the jQuery .animate() method for smooth transition. Change you code as below.

$('#page_header_logo_img').animate({
  "padding-left": "20%",
  "display": "inline"
})

and

$('#page_header_logo_img').animate({
  "padding-left": "0",
  "display": "block"
})

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