Domanda

I have a problem with animating a font when is scrolls past the viewport height. It can animate once but not back again...

This works, it just changes the font size back and forth:

if ($(this).scrollTop() > $( window ).height()) {
               $('.nav li a').css({"font-size":"2vw"});
            } else {
               $('.nav li a').css({"font-size":"1.2vw"});
            }

But this does not, it animates once but then starts to lag and jump when it should animate back:

            if ($(this).scrollTop() > $( window ).height()) {
               $('.nav li a').animate({"font-size":"2vw"});
            } else {
               $('.nav li a').animate({"font-size":"1.2vw"});
            }

Does anyone know why? Thanks!

È stato utile?

Soluzione

Does this need to be animated in jQuery? You can get your effect with CSS3 transitions (unless you're trying to support older browsers):

transition: all 0.3s ease;
-webkit-transition: all 0.3s ease;
-moz-transition: all 0.3s ease;
-o-transition: all 0.3s ease;
-ms-transition: all 0.3s ease;

Or font only:

transition: font 0.3s ease;
-webkit-transition: font 0.3s ease;
-moz-transition: font 0.3s ease;
-o-transition: font 0.3s ease;
-ms-transition: font 0.3s ease;

You can then use the .css() method to change font-size and the CSS transition will handle the animation.

Altri suggerimenti

Just in case the problem is you calling animate too many times, you may try something like this (untested code, sorry I can't try it now):

var newState=$(this).scrollTop() > $( window ).height();


function updateOnScroll(e) {

    var oldState=newState;

    newState=$(this).scrollTop() > $( window ).height();

    if(oldState!=newState) {
        if(newState) {
            $('.nav li a').animate({"font-size":"100vw"});
        } else {
            $('.nav li a').animate({"font-size":"1.2vw"});
        }
     }
}

Just an idea...

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top