Make a div appear when scrolling past a certain po

2019-01-23 07:01发布

问题:

My goal is to make a fixed div appear at the top of a page once someone scrolls a certain amount of pixels down the page. Basically once the header section is out of view, this div will appear.

I've looked at code similar to what I want; however, haven't seen anything that would allow me to easily modify the pixel count from the top of the page (if possible).

Here is a piece of code I saw dealing with making divs appear by scrolling.

// Get the headers position from the top of the page, plus its own height
var startY = $('header').position().top + $('header').outerHeight();

$(window).scroll(function(){
    checkY();
});

function checkY(){
    if( $(window).scrollTop() > startY ){
        $('.fixedDiv').slideDown();
    }else{
        $('.fixedDiv').slideUp();
    }
}

// Do this on load just in case the user starts half way down the page
checkY();

I just want to know how to make it appear. If someone knows of a piece of code already in tact with a slide up and slide down animation, that would be greatly appreciated as well but not required.

回答1:

window.addEventListener("scroll",function() { 
   if(window.scrollY > 500) {
      $('.fixedDiv').slideDown();
   }
   else {
      $('.fixedDiv').slideUp();
   }
},false);


回答2:

Brandon Tilley answered my question in a comment...

You would change the first line, with the startY, to be the specific Y position you need, rather than calculating based on the header's position and height. Here's an updated fiddle: jsfiddle.net/BinaryMuse/Ehney/1



回答3:

window.addEventListener("scroll",function() { 
   $('.fixedDiv')[(window.scrollY > 500)?"slideDown":"slideUp"]();
},false);

DEMO: http://jsfiddle.net/DerekL/8eG2A/