简体   繁体   中英

How to add fade effect while changing CSS with JQuery

I am faking fixed position for a footer on a mobile site for mobile browsers that don't support fixed-position. (iOS before iOS 5, Andriod before 2.2, etc.)

Here is the JQuery code I'm using, which works well and does what I want:

function changeFooterPosition() {   
  $('.not-fixed').css('top', window.innerHeight + window.scrollY - 56 + "px");
}

$(document).bind('scroll', function() {
  changeFooterPosition();
}); 

So that works.

My question is, I want to add a slight delay to it and have the footer fade into view rather than just snap quickly after every little scroll. I've looked around and found the following methods I could use, but I"m not sure if they are the correct ones or where to add them to the js above.

.delay(1000).fadeTo('slow', 1)

I know this functionality exists in JQuery Mobile, but I don't want to use the entirety of JQuery Mobile for just this one little thing.

Thanks in advance.

Try the animate function http://api.jquery.com/animate/

This won't fade but should move smoothly instead.

function changeFooterPosition() {   
  $('.not-fixed').animate({'top': window.innerHeight + window.scrollY - 56 + "px"}, 2000);
}

$(document).bind('scroll', changeFooterPosition); 

Change

$(document).bind('scroll', function() {
  changeFooterPosition();
}); 

To

$(document).bind('scroll', changeFooterPosition); 

Change

$('.not-fixed').css('top', window.innerHeight + window.scrollY - 56 + "px");

to

var WantedSpeed = 2000;
$('.not-fixed').delay(1000).animate({
    top: window.innerHeight + window.scrollY - 56 + "px"
}, WantedSpeed, function() {
    // Animation complete.
})

What you want to do is throttle your scroll callback:

(function() {
  var scrollTimer = 0,
      $notFixed = $('.not-fixed');

  function changeFooterPosition() {   
    $notFixed.css('top', window.innerHeight + window.scrollY - 56 + "px").show(300);
  }

  $(document).bind('scroll', function() {
    $notFixed.hide();
    clearTimeout(scrollTimer);
    setTimeout(changeFooterPosition, 50);
  });
}());

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