javascript 滚动经过页面的某个点时显示 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13549214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Make a div appear when scrolling past a certain point of a page
提问by kdjernigan
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.
我的目标是在有人向下滚动页面一定数量的像素时,在页面顶部显示一个固定的 div。基本上,一旦标题部分不在视野中,就会出现这个 div。
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.
这是我看到的一段代码,用于通过滚动显示 div。
// 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.
我只想知道如何让它出现。如果有人知道一段带有向上和向下滑动动画的代码,那将不胜感激,但不是必需的。
回答by lostsource
window.addEventListener("scroll",function() {
if(window.scrollY > 500) {
$('.fixedDiv').slideDown();
}
else {
$('.fixedDiv').slideUp();
}
},false);
回答by kdjernigan
Brandon Tilley answered my question in a comment...
Brandon Tilley 在评论中回答了我的问题......
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
您可以将带有 startY 的第一行更改为您需要的特定 Y 位置,而不是根据标题的位置和高度进行计算。这是一个更新的小提琴:jsfiddle.net/BinaryMuse/Ehney/1
回答by u283863
window.addEventListener("scroll",function() {
$('.fixedDiv')[(window.scrollY > 500)?"slideDown":"slideUp"]();
},false);