gpt4 book ai didi

javascript - 通过 jQuery 在某个滚动级别更改 CSS 不起作用

转载 作者:搜寻专家 更新时间:2023-10-31 23:03:10 25 4
gpt4 key购买 nike

以下 jQuery 代码:

Click here

HTML:
<header class="header">
<div class="navbar">
Hello
</div>
</header>

CSS:
.header {
background-color: black;
height: 1000px;
width: 300px;
color: white;
text-align: center;
padding: 30px;
}

.fixed .navbar{
border: 10px solid red;
position: fixed;
background-color: white;
}

.navbar {
background-color: blue;
height: 50px;
width: 300px;
color: white;
}

JS:
$(window).scroll( function(){
if($(window).scrollTop() > 200) $("header").addClass("fixed");
else $("header").removeClass("fixed");
});

确实有效。

但是当我将它添加到我的主页时,我必须刷新页面才能添加“固定”类。但我希望在向下滚动的同时实时添加类(class),而无需刷新页面。这在 jsfiddle 中有效,为什么它在我的页面上无效?

我的页面:Click here

最佳答案

正如 Karl-André 所说,您的 $ 对象正在被覆盖。要使您的代码正常工作,您可以执行以下任一操作:

使用 jQuery 对象:

jQuery(window).scroll( function(){
if(jQuery(window).scrollTop() > 200) jQuery("header").addClass("fixed");
else jQuery("header").removeClass("fixed");
});

或者将所有内容包装在一个自执行函数中,将 jQuery 对象作为参数传递:

(function($)
{
$(window).scroll( function(){
if($(window).scrollTop() > 200) $("header").addClass("fixed");
else $("header").removeClass("fixed");
});
}(jQuery))

关于javascript - 通过 jQuery 在某个滚动级别更改 CSS 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24938087/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com