[英]jQuery bind function to parent div but not child anchor and vice-versa
[英]codepen: jQuery .css() edit when scrolldown past anchor, vice versa
codepen http://codepen.io/mathiasvanderbrempt/pen/mJjjrx
我需要弄清楚為什么這個jQuery不起作用...
我想在.navigationfx
的scrolltop()到達第一部分時使其下拉(頂部= 0px)(我應該添加類還是ID?)。 因此,當它向后滾動過去時,我想使其向上移動(頂部= -30px)。
$(function(){
//last scroll will always save the current scroll position value
var CurrentScroll = 0;
$(window).scroll(function(event){
var NextScroll = $(this).scrollTop();
if (NextScroll > CurrentScroll){
//codes related to down-ward scrolling here
if ($(window).scrollTop() > $('section').scrollTop())
{
$('navigationfx').css('top', '0px')
}
else {
$('navigationfx').css('top', '-100px')
}
}
else {
//codes related to upward-scrolling here
if ($(window).scrollTop() < $('section').scrollTop())
{
$('navigationfx').css('top', '-100px')
}
else {
$('navigationfx').css('top', '0px')
}
}
//Updates current scroll position
CurrentScroll = NextScroll;
});
});
的CSS
.navigationfx {
visibility: ;
position: fixed;
z-index: 2;
margin: 0 auto;
padding: 5px 0 0 0;
width: 100%;
top: -50px;
left: 0;
background: rgba(250,250,250,0.5);
text-align: center;
color: #333;
border-bottom: 1px solid #dddedf
}
一些事情:
您從匹配集中選擇第一部分為:
$('section').first();
由於該部分沒有滾動,因此您必須將offset top用作:
$('section').first().offset().top;
不要一遍又一遍地掃描DOM來查找同一元素。 存儲參考,並根據需要使用它:
var $nav = $(".navigationfx");
var $firstSection = $('section').first();
不確定這是否是您想要的,但是,這是您的筆更新的
PS可以使用.css()
添加/更新此特定方案的top
,而不必添加/刪除類。
因為$('section').scrollTop()
永久等於0
。
將其更改為$("section").offset().top
。
當您將$('section').scrollTop()
登錄到控制台時,您將看到它始終返回零。 而是使用$('section').offset().top
。
您還缺少一個.
在navigationfx選擇器中。
$(function(){
//last scroll will always save the current scroll position value
var CurrentScroll = 0;
$(window).scroll(function(event){
var NextScroll = $(this).scrollTop();
if (NextScroll > CurrentScroll){
//codes related to down-ward scrolling here
if($(window).scrollTop() > $('section').offset().top)
{
$('.navigationfx').css('top', '0px')
}
else {
$('.navigationfx').css('top', '-100px')
}
}
else {
//codes related to upward-scrolling here
if($(window).scrollTop() < $('section').offset().top)
{
$('.navigationfx').css('top', '-100px')
}
else {
$('.navigationfx').css('top', '0px')
}
}
//Updates current scroll position
CurrentScroll = NextScroll;
});
});
$('navigationfx') => $('.navigationfx')
我認為所有這些代碼都可以簡化為:
$(function(){
$(window).scroll(function(event){
var offset = $(window).scrollTop() > $('section').offset().top?'0px':'-100px';
$('.navigationfx').css('top', offset);
});
$(window).scroll();
});
codepen: http ://codepen.io/anon/pen/YXjJLG
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.