jQuery滚动并更改类

时间:2015-09-01 09:22:19

标签: javascript jquery css scroll

我正在尝试向我的网站添加以下功能:当用户向下滚动超过400像素时,页面的第一部分应为不透明度:0.4。这是我已经无法尝试的代码:

if($("html, body").offset().top >= 400){$("#main").addClass("scrolled");}

.scrolled {opacity:0.4;}

jquery函数有效,所以我猜没有语法错误。

感谢您的回答。

2 个答案:

答案 0 :(得分:0)

我猜您正在寻找.scrollTop()而非.offset().top导致负数,因为html,body已经有.offset().top0 @ page加载,当您在y轴滚动时会得到一个负数:

if($(document).scrollTop() >= 400){
     $("#main").addClass("scrolled");
}

如果您想使用$(document),请使用.scrollTop()作为选择器,我想您已经在那里举行了.scroll活动。

注意:

$("html, body").offset().top此选择器的结果为负.offset().top,因为html,body .offset().top已经0轴x / y到DOMContentLoaded $(function() { $('.redactor1').redactor({ focus: true, toolbarExternal: '#toolbar' }); }); $(document).click(function(){ $("#toolbar_wrapper").hide(); }); $("#toolbar_wrapper").click(function(e){ e.stopPropagation(); $("#toolbar_wrapper").css('display','block'); }); $(".redactor").click(function(e){ e.stopPropagation(); $("#toolbar_wrapper").css('display','block'); }); 事件被解雇。所以当你垂直滚动时,你实际上是滚动到y轴,这是一个负数

答案 1 :(得分:0)

你想给每次滚动位置改变时调用的$.scroll回调,然后检查你是否足够远。

$(document).scroll(function(){
    // check the document scroll position
    if($(document).scrollTop() >= 400){
         $("#main").addClass("scrolled");
    } else {
         // if you also want to put #main back to normal
         $("#main").removeClass("scrolled");
    }
});

Here is a jsfiddle