确定元素位于视口底部并向其添加 class?
Determine element is at bottom of viewport and add class to it?
这里需要一些帮助。我需要确定某个元素何时位于视口的底部位置,然后向其添加 fixed class 。因此,当元素位于底部 0 时向下滚动添加 class,当我向上滚动时删除 class。
$(window).scroll(function() {
var $el = $('.content-btn-row');
if ($($el).position().top + $($el).height()) {
console.log("bottom!");
$(".content-btn-row").addClass("fixed");
} else {
$(".scontent-btn-row").removeClass("fixed");
}
});
IMO 我们应该考虑 window 内容区域的内部高度(window 高度可能不同)并检查文档是否已滚动。
window.innerHeight
- returns window 内容区域的内部高度
window.pageYOffset
- returns 当前文档从 window
左上角滚动(垂直)的像素
如果元素在开始时位于视口下方,则此代码应该没问题:
var elem = window.innerHeight + $($el).height(); //position of the element
var winScroll = window.innerHeight + window.pageYOffset; //viewport height + scroll
if (elem) >= (winScroll) {
console.log("bottom!");
$(".content-btn-row").addClass("fixed");
} else {
$(".scontent-btn-row").removeClass("fixed");
}
}
并且在我们添加或删除它之前,最好检查是否有 class "fixed" 和 hasClass
。
为什么要通过添加相同的常量值 (window.innerHeight) 来比较变量?
var elem = $($el).height();
var winScroll = window.pageYOffset;
if (elem) >= (winScroll) {
console.log("bottom!");
$(".content-btn-row").addClass("fixed");
} else {
$(".scontent-btn-row").removeClass("fixed");
}}
通过这种方式我们可以减少一些复杂性和代码
这里需要一些帮助。我需要确定某个元素何时位于视口的底部位置,然后向其添加 fixed class 。因此,当元素位于底部 0 时向下滚动添加 class,当我向上滚动时删除 class。
$(window).scroll(function() {
var $el = $('.content-btn-row');
if ($($el).position().top + $($el).height()) {
console.log("bottom!");
$(".content-btn-row").addClass("fixed");
} else {
$(".scontent-btn-row").removeClass("fixed");
}
});
IMO 我们应该考虑 window 内容区域的内部高度(window 高度可能不同)并检查文档是否已滚动。
window.innerHeight
- returns window 内容区域的内部高度
window.pageYOffset
- returns 当前文档从 window
左上角滚动(垂直)的像素
如果元素在开始时位于视口下方,则此代码应该没问题:
var elem = window.innerHeight + $($el).height(); //position of the element
var winScroll = window.innerHeight + window.pageYOffset; //viewport height + scroll
if (elem) >= (winScroll) {
console.log("bottom!");
$(".content-btn-row").addClass("fixed");
} else {
$(".scontent-btn-row").removeClass("fixed");
}
}
并且在我们添加或删除它之前,最好检查是否有 class "fixed" 和 hasClass
。
为什么要通过添加相同的常量值 (window.innerHeight) 来比较变量?
var elem = $($el).height();
var winScroll = window.pageYOffset;
if (elem) >= (winScroll) {
console.log("bottom!");
$(".content-btn-row").addClass("fixed");
} else {
$(".scontent-btn-row").removeClass("fixed");
}}
通过这种方式我们可以减少一些复杂性和代码