繁体   English   中英

jQuery 滚动和更改类

[英]jQuery scrolling and changing the class

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

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

.scrolled {opacity:0.4;}

jquery 函数可以工作,所以我猜没有语法错误。

谢谢你的任何回答。

我猜你正在寻找.scrollTop()而不是.offset().top这会导致负数作为html,body已经有.offset().top0 @ 页面加载,当你在 y 滚动时轴结果为负数:

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

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


笔记:

$("html, body").offset().top这个选择器的结果是负的.offset().top因为当DOMContentLoaded事件触发时html,body已经有.offset().top轴 x/y 到0 . 所以当你垂直滚动时,你实际上是滚动到 y 轴,这是一个负数

你想给$.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");
    }
});

这是一个 jsfiddle

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM