开发者

How do I animate elements with jQuery?

开发者 https://www.devze.com 2022-12-14 07:14 出处:网络
How do I say, slide an element a few pixels to the side from its initial position using jQuery? I know there is an animate() function but I have no idea how to use it.

How do I say, slide an element a few pixels to the side from its initial position using jQuery? I know there is an animate() function but I have no idea how to use it. Tips, tutorials would be appreciated.

EDIT:

I am now trying to change the background color of an element on mouseover (I would also like to swap background images eventually, but that's 开发者_如何学运维not for now...)

I'm currently using the following code. what's wrong? (.link is a class referring to a bunch of a elements)

  //light up links on  mouseover
  $(".link").mouseover(function(event){           
    $(this).animate({'color' : '#000099'}, "fast");
  });

  //dim link on mouseout
  $(".link").mouseout(function(event){       
    $(this).animate({'color' : '#efefef'}, "fast");                
  });


First, read the documentation for animate.

Then, you must define the element you are trying to move to have its position attribute set to relative or absolute via CSS or jQuery.

If you set it to relative, you can just supply the amount of pixels you want to move it with:

// Will move #element right 10 pixels in 500 milliseconds
$('#element').animate({
    left: 10px
}, 500);

If you chose absolute positioning, you must first work out the starting position of the element using .offset().left and add the desired amount of pixels to that, then animate to that position. For example:

// Will move #element right 10 pixels in 500 milliseconds
$('#element').animate({
    left: $('#element').offset().left + 10
}, 500);

This works if the #element's parent elements are statically positioned (otherwise the offset().left doesn't match with the absolute left value).


For color animations, you need to use the jQuery color plugin.

You can use animate() to animate colors when you import the jQuery Color plugin.


When thinking about positional animation, you need to keep in mind that you're still just playing with the CSS. So in your case where you want to slide over to the left a bit, you'll be wanting to adjust the left-hand margin (or potentially add padding to the right, depending on your existing styles and layout).

For example:

$("#myElement").click(function(){
  $(".block").animate({"left": "-=50px"}, "slow");
});

This site has some useful content on basic animation and of course there is the actual jQuery documentation.


i am really love this site , its a great recourse about jQuery

jQuery for Designers

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号