当元素位于屏幕顶部时将 Class 添加到元素
Adding Class to Element when it's at the Top of the Screen
我正在尝试将 class 添加到点击父级 DIV 内的按钮或在输入表单中输入文本后附加到屏幕顶部的元素。
它有效,但不适用于附加元素。当它确实适用于附加元素时,就像这些元素的偏移量在每次附加时都会消失,然后它将 class 应用于之后的每个附加元素。这很烦人,我已经坚持了至少一个星期了。
当元素到达屏幕顶部时,我用来添加 class 的代码是这样的:
window.poo = function poo() {
$("#message").each(function() {
var win = $(".chat-log"),
nav = $(this),
pos = nav.offset().top,
sticky = function() {
win.scrollTop() > pos ?
nav.addClass('inactive') :
nav.removeClass('inactive')
}
win.scroll(sticky);
});
}
poo();
元素的父元素是 #message 而 #message 的父元素是 .chat-log。我已将 #message 更改为 .message 但它仍然给了我相同的结果。
并且当用户单击父项中的按钮时,每次偏移都会变得更糟,并且 class 会在所有元素到达屏幕顶部之前应用到所有元素。
您似乎在尝试将函数附加到每个 .chat-log
div,因此它会在滚动时执行。问题是当它执行时,只有一个这样的div,所以只有在通过顶部时它才会改变它的class。
您必须更改函数,使 for each
位于每次滚动时执行的函数内。例如,您可以将它附加到 window,然后在其中搜索应该应用样式的 div。
$(".chat-log").on("scroll", function() {
console.log("I'm scrolling!");
var win = $(this); // .chat-log
win.find(".message").each(function(){
var nav = $(this); // each .message found
//console.log("win: "+win.scrollTop());
console.log("nav: "+nav.offset().top);
nav.offset().top < 0 ? nav.addClass('inactive') : nav.removeClass('inactive')
});
});
我正在尝试将 class 添加到点击父级 DIV 内的按钮或在输入表单中输入文本后附加到屏幕顶部的元素。
它有效,但不适用于附加元素。当它确实适用于附加元素时,就像这些元素的偏移量在每次附加时都会消失,然后它将 class 应用于之后的每个附加元素。这很烦人,我已经坚持了至少一个星期了。
当元素到达屏幕顶部时,我用来添加 class 的代码是这样的:
window.poo = function poo() {
$("#message").each(function() {
var win = $(".chat-log"),
nav = $(this),
pos = nav.offset().top,
sticky = function() {
win.scrollTop() > pos ?
nav.addClass('inactive') :
nav.removeClass('inactive')
}
win.scroll(sticky);
});
}
poo();
元素的父元素是 #message 而 #message 的父元素是 .chat-log。我已将 #message 更改为 .message 但它仍然给了我相同的结果。
并且当用户单击父项中的按钮时,每次偏移都会变得更糟,并且 class 会在所有元素到达屏幕顶部之前应用到所有元素。
您似乎在尝试将函数附加到每个 .chat-log
div,因此它会在滚动时执行。问题是当它执行时,只有一个这样的div,所以只有在通过顶部时它才会改变它的class。
您必须更改函数,使 for each
位于每次滚动时执行的函数内。例如,您可以将它附加到 window,然后在其中搜索应该应用样式的 div。
$(".chat-log").on("scroll", function() {
console.log("I'm scrolling!");
var win = $(this); // .chat-log
win.find(".message").each(function(){
var nav = $(this); // each .message found
//console.log("win: "+win.scrollTop());
console.log("nav: "+nav.offset().top);
nav.offset().top < 0 ? nav.addClass('inactive') : nav.removeClass('inactive')
});
});