简体   繁体   中英

Animate element using JQuery

I've been playing around with JQuery and had a few questions.

I would like to animate an element from off screen to it's position after the page is fully loaded.

I have the effect I like, but I feel i approached it from the wrong way. I am positioning the element off page with CSS and using Jquery to move it to the correct spot. Is this normal?

Here is my example:

JQuery

$(document).ready(function() {  
  $( "#box" ).animate({
    top: "62px",
  }, 1000, function() {
    // Animation complete.
  });   
});

CSS

#box {
  width: 100%;
  height: 62px;
  background-color: black;
  position: absolute;
  margin-top: -62px;
}

http://codepen.io/Legym/pen/vEbJqG/

You can set box style to display:none; :

#box {
  width: 100%;
  height: 62px;
  background-color: black;
  display:none;
}

and then show it

$(document).ready(function() {  
  $( "#box" ).show('slow');
  });   

I'm not sure what industry standard is, but if you're willing to forsake some early IE 8 compatibility I can offer an alternative using CSS3;

.boxSlideIn{
  animation: slideDown 2s;
  -webkit-animation: slideDown 2s;
}

@-webkit-keyframes slideDown{
  from {top: -62px;}
  to {top: 0px;}
}

@keyframes slideDown{
  from {top: -62px;}
  to {top: 0px;}
}

Then onload just add the class

$(document).ready(function(){
    $('#box').addClass('boxSlideIn');
});

This gives it the proper CSS off the bat, without any weird negative margins. Also you can customize it to your liking.

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