简体   繁体   中英

Div fades opacity out when user scrolls to just before the bottom of each page

I am currently making a site with an arrow implying the user to scroll down. I have managed to get this code below which gives a very nice fade in and out of the icon but I want to have the icon opacity to start fading away about 300px from the bottom of every page on my site.

$(window).scroll(function(){
   $(".down-arrow").css("opacity", 1 - $(window).scrollTop() / 300);
});

Each page is different lengths so if someone could point me in the right direction of getting this animation to apply 300px from the bottom of each page that would be amazing!

Cheers!

Edit - I have made a jsfiddle.net to with the code I am currently using: https://jsfiddle.net/euty0oon/

Here's fadeToBottom() wrapped as a tiny jQuery plugin:

$.fn.fadeToBottom = function(d) {
  var w=$(window), 
      f=()=>{$(this).css({opacity:Math.min($('body')[0].scrollHeight-w.scrollTop()-w.height(),d)/d})};
  if(d)w.on('load scroll resize',f)
}

Use as

$('.down-arrow').fadeToBottom(300);

Your updated fiddle .


If you care about page performance, use the version below, ( especially if you use it on more than one element on same page! ) making sure you load Ben Alman's debounce/throttle first (depends on it):

$.fn.fadeToBottom = function(d) {
  var w=$(window), 
      f=()=>{$(this).css({opacity:Math.min($('body')[0].scrollHeight-w.scrollTop()-w.height(),d)/d})};
  $(this).css({transition:'opacity 42ms'});
  if(d)w.on('load scroll resize',$.throttle(42,f))
}

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