简体   繁体   中英

Recreating an animation using jQuery and CSS

I've been working on a scrolling effect for my site that has been driving me crazy, and it's probably not even worth it but I can't stop now.

I have been able to simulate the effect using adobe edge and muse. Can anyone think of a simpler method of creating this effect? The animation can be seen here . As you scroll, the header shape changes and resizes. I have tried doing this with svg animate, div rotation animate, etc. with no luck.

Any help would be appreciated.

Normally we don't provide full solutions for questions, but I had some free time and this was a pretty fun project. If my answer works for you I hope you'll accept it.

I'm sure there are more efficient ways to do this (manipulating an SVG for example), but I kept this as succinct as I possibly could. This is using CSS and Javascript / jQuery. I'll let the comments in the javascript portion do the explaining.

HTML

<div id="animation">
  <div id="box"></div>
  <div id="ang"></div>
</div>

CSS

#animation {
  width: 500px;
  position: fixed;
  top: 0;
  left: 50%;
  margin-left: -250px;
}

#box {
  width: 500px;
  height: 125px;
  background: #333;
}

#ang {
  width: 0;
  height: 0;
  border-top: 175px solid #333;
  border-right: 500px solid transparent;
}

Javascript

$(window).scroll(function() {
  var pos = $(window).scrollTop(), // Current scroll position
      max = 300, // How quickly we want the animation to finish (in pixels)
      box = 50, // Collapsed height of the box
      ang = 0; // Collapsed height of the angle

  /* Only make changes if we are within the limit of our max variable
   * If this condition is not met, the box and angle will be collapsed
   * I found this necessary because scrollTop doesn't produce consistent
   * values and quite often the box wouldn't fully collapse */
  if (pos <= max) {
    // Max height - (scroll percentage x (max height - min height))
    box = 125 - (pos / max * 75);
    ang = 175 - (pos / max * 175);
  }

  // Adjust the height of the box and the angle
  $('#box').css({ 'height': box + 'px' });
  $('#ang').css({ 'border-top-width': ang + 'px' });
});

See my JS Bin for a demo.

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