Javascript 使用基于垂直滚动的 jquery 添加/删除类?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12558311/
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
Add/remove class with jquery based on vertical scroll?
提问by andy
So basically I'd like to remove the class from 'header' after the user scrolls down a little and add another class to change it's look.
所以基本上我想在用户向下滚动一点并添加另一个类以更改它的外观后从“标题”中删除该类。
Trying to figure out the simplest way of doing this but I can't make it work.
试图找出最简单的方法来做到这一点,但我无法让它发挥作用。
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll <= 500) {
$(".clearheader").removeClass("clearHeader").addClass("darkHeader");
}
}
CSS
CSS
.clearHeader{
height: 200px;
background-color: rgba(107,107,107,0.66);
position: fixed;
top:200;
width: 100%;
}
.darkHeader { height: 100px; }
.wrapper {
height:2000px;
}
HTML
HTML
<header class="clearHeader"> </header>
<div class="wrapper"> </div>
I'm sure I'm doing something very elementary wrong.
我确定我在做一些非常基本的错误。
回答by Fabrício Matté
$(window).scroll(function() {
var scroll = $(window).scrollTop();
//>=, not <=
if (scroll >= 500) {
//clearHeader, not clearheader - caps H
$(".clearHeader").addClass("darkHeader");
}
}); //missing );
Also, by removing the clearHeader
class, you're removing the position:fixed;
from the element as well as the ability of re-selecting it through the $(".clearHeader")
selector. I'd suggest not removing that class and adding a new CSS class on top of it for styling purposes.
此外,通过删除clearHeader
类,您position:fixed;
将从元素中删除以及通过$(".clearHeader")
选择器重新选择它的能力。我建议不要删除该类并在其上添加一个新的 CSS 类以用于样式目的。
And if you want to "reset" the class addition when the users scrolls back up:
如果您想在用户向上滚动时“重置”类添加:
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 500) {
$(".clearHeader").addClass("darkHeader");
} else {
$(".clearHeader").removeClass("darkHeader");
}
});
edit:Here's version caching the header selector - better performance as it won't query the DOM every time you scroll and you can safely remove/add any class to the header element without losing the reference:
编辑:这是缓存标题选择器的版本 - 更好的性能,因为它不会在每次滚动时查询 DOM,并且您可以安全地删除/添加任何类到标题元素而不会丢失引用:
$(function() {
//caches a jQuery object containing the header element
var header = $(".clearHeader");
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 500) {
header.removeClass('clearHeader').addClass("darkHeader");
} else {
header.removeClass("darkHeader").addClass('clearHeader');
}
});
});
回答by Marc
Add some transition effect to it if you like:
如果您愿意,可以为其添加一些过渡效果:
http://jsbin.com/boreme/17/edit?html,css,js
http://jsbin.com/boreme/17/edit?html,css,js
.clearHeader {
height:50px;
background:lightblue;
position:fixed;
top:0;
left:0;
width:100%;
-webkit-transition: background 2s; /* For Safari 3.1 to 6.0 */
transition: background 2s;
}
.clearHeader.darkHeader {
background:#000;
}
回答by Shahzad Yousuf
Its my code
它的我的代码
jQuery(document).ready(function(e) {
var WindowHeight = jQuery(window).height();
var load_element = 0;
//position of element
var scroll_position = jQuery('.product-bottom').offset().top;
var screen_height = jQuery(window).height();
var activation_offset = 0;
var max_scroll_height = jQuery('body').height() + screen_height;
var scroll_activation_point = scroll_position - (screen_height * activation_offset);
jQuery(window).on('scroll', function(e) {
var y_scroll_pos = window.pageYOffset;
var element_in_view = y_scroll_pos > scroll_activation_point;
var has_reached_bottom_of_page = max_scroll_height <= y_scroll_pos && !element_in_view;
if (element_in_view || has_reached_bottom_of_page) {
jQuery('.product-bottom').addClass("change");
} else {
jQuery('.product-bottom').removeClass("change");
}
});
});
Its working Fine
它的工作正常
回答by ido
Is this value intended? if (scroll <= 500) { ...
This means it's happening from 0 to 500, and not 500 and greater. In the original post you said "after the user scrolls down a little"
这个值是有意的吗?if (scroll <= 500) { ...
这意味着它发生在 0 到 500 之间,而不是 500 和更大。在原始帖子中,您说“在用户向下滚动一点之后”
回答by chrisbergr
In a similar case, I wanted to avoid always calling addClass or removeClass due to performance issues. I've split the scroll handler function into two individual functions, used according to the current state. I also added a debounce functionality according to this article: https://developers.google.com/web/fundamentals/performance/rendering/debounce-your-input-handlers
在类似的情况下,由于性能问题,我想避免总是调用 addClass 或 removeClass。我已将滚动处理程序函数拆分为两个单独的函数,根据当前状态使用。我还根据这篇文章添加了去抖动功能:https: //developers.google.com/web/fundamentals/performance/rendering/debounce-your-input-handlers
var $header = jQuery( ".clearHeader" );
var appScroll = appScrollForward;
var appScrollPosition = 0;
var scheduledAnimationFrame = false;
function appScrollReverse() {
scheduledAnimationFrame = false;
if ( appScrollPosition > 500 )
return;
$header.removeClass( "darkHeader" );
appScroll = appScrollForward;
}
function appScrollForward() {
scheduledAnimationFrame = false;
if ( appScrollPosition < 500 )
return;
$header.addClass( "darkHeader" );
appScroll = appScrollReverse;
}
function appScrollHandler() {
appScrollPosition = window.pageYOffset;
if ( scheduledAnimationFrame )
return;
scheduledAnimationFrame = true;
requestAnimationFrame( appScroll );
}
jQuery( window ).scroll( appScrollHandler );
Maybe someone finds this helpful.
也许有人觉得这很有帮助。
回答by ego
Here's pure javascript example of handling classes during scrolling.
这是在滚动期间处理类的纯 javascript 示例。
You'd probably want to throttle handling scroll events, more so as handler logic gets more complex, in that case throttle
from lodash
lib comes in handy.
你可能会想掐死处理滚动事件,更使处理程序逻辑变得越来越复杂,在这种情况下throttle
从lodash
LIB就派上用场了。
And if you're doing spa, keep in mind that you need to clear event listeners with removeEventListener
once they're not needed (eg during onDestroy
lifecycle hook of your component, like destroyed()
for Vue, or maybe return function of useEffect
hook for React).
如果您正在做 spa,请记住,您需要在不需要时清除事件侦听器removeEventListener
(例如,在onDestroy
组件的生命周期钩子期间,例如destroyed()
Vue,或者可能useEffect
是 React 钩子的返回函数)。
const navbar = document.getElementById('navbar')
// OnScroll event handler
const onScroll = () => {
// Get scroll value
const scroll = document.documentElement.scrollTop
// If scroll value is more than 0 - add class
if (scroll > 0) {
navbar.classList.add("scrolled");
} else {
navbar.classList.remove("scrolled")
}
}
// Optional - throttling onScroll handler at 100ms with lodash
const throttledOnScroll = _.throttle(onScroll, 100, {})
// Use either onScroll or throttledOnScroll
window.addEventListener('scroll', onScroll)
#navbar {
position: fixed;
top: 0;
left: 0;
right: 0;
width: 100%;
height: 60px;
background-color: #89d0f7;
box-shadow: 0px 5px 0px rgba(0, 0, 0, 0);
transition: box-shadow 500ms;
}
#navbar.scrolled {
box-shadow: 0px 5px 10px rgba(0, 0, 0, 0.25);
}
#content {
height: 3000px;
margin-top: 60px;
}
<!-- Optional - lodash library, used for throttlin onScroll handler-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
<header id="navbar"></header>
<div id="content"></div>
回答by user9261696
For Android mobile $(window).scroll(function() and $(document).scroll(function() may or may not work. So instead use the following.
对于 Android 移动设备 $(window).scroll(function() 和 $(document).scroll(function() 可能有效也可能无效。因此请改用以下内容。
jQuery(document.body).scroll(function() {
var scroll = jQuery(document.body).scrollTop();
if (scroll >= 300) {
//alert();
header.addClass("sticky");
} else {
header.removeClass('sticky');
}
});
This code worked for me. Hope it will help you.
这段代码对我有用。希望它会帮助你。