Make a div appear when scrolling past a certain po

2019-01-23 06:46发布

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.

3条回答
放我归山
2楼-- · 2019-01-23 07:31
window.addEventListener("scroll",function() { 
   if(window.scrollY > 500) {
      $('.fixedDiv').slideDown();
   }
   else {
      $('.fixedDiv').slideUp();
   }
},false);
查看更多
做个烂人
3楼-- · 2019-01-23 07:32

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

查看更多
我只想做你的唯一
4楼-- · 2019-01-23 07:37
window.addEventListener("scroll",function() { 
   $('.fixedDiv')[(window.scrollY > 500)?"slideDown":"slideUp"]();
},false);

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

查看更多
登录 后发表回答