if 语句中的 JQuery .scrollTop
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9855195/
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
JQuery .scrollTop in an if statement
提问by Erik Manley
if ($(body).scrollTop() > 120px)
{
document.getElementByID("head").ID = "headfixed"
}
this doesn't work, and I'm not surprised, but nowhere I look helps me with what I want to do. Can I get some help on this? thanks in advance.
这是行不通的,我并不感到惊讶,但是我所看到的任何地方都无法帮助我完成我想做的事情。我能得到一些帮助吗?提前致谢。
回答by Brian Noah
Question: why are you using a combination of element selectors with jQuery, and "getElementById"? Here's how I'd re-write your function.... You need to put this if statement in a function that occurs when something happens. In this case, it' when the window scrolls.
问题:为什么要结合使用元素选择器与 jQuery 和“getElementById”?这是我如何重写您的函数.... 您需要将此 if 语句放在发生某些事情时发生的函数中。在这种情况下,它是在窗口滚动时。
$(window).scroll(function () {
var $this = $(this),
$head = $('#head');
if ($this.scrollTop() > 120) {
$head.addClass('fixed_header');
} else {
$head.removeClass('fixed_header');
}
});
Does this make sense? also, scrollTop doesn't go off of pixels, but it's an integer. By the way, only window and this can go in the parens without quotes... body, html, etc.... need quotes around them when being selected.
这有意义吗?此外, scrollTop 不会关闭像素,但它是一个整数。顺便说一句,只有 window 和 this 可以在没有引号的情况下进入括号...... body,html等......在被选中时需要在它们周围加上引号。
回答by Whymarrh
I think the value that you are looking for is .offset().top
. That will return the current position of $elem
relative to the top of the document.
我认为您正在寻找的价值是.offset().top
. 这将返回$elem
相对于文档顶部的当前位置。
// below: the offset of the body tag to the top of the page
$("body").offset().top
// below: the offset of the element with the id #head to the top of the page
$("#head").offset().top
回答by Gohn67
I think scroll top returns an integer value, so your comparison value should be 120 and not 120px.
我认为滚动顶部返回一个整数值,所以你的比较值应该是 120 而不是 120px。
EDIT:
编辑:
Additionally, do you get a syntax error for 120px, since it is not wrapped in quotes? When I tested in jsfiddle, I got the following error in Firebug:
此外,您是否收到 120px 的语法错误,因为它没有用引号括起来?当我在 jsfiddle 中测试时,在 Firebug 中出现以下错误:
identifier starts immediately after numeric literal
identifier starts immediately after numeric literal
回答by Alejandro Santamaría
you must make sure that 'if condition' is in the scroll function.
您必须确保“如果条件”在滚动功能中。
function scroll() {
if ($(body).scrollTop() > 120px)
{
document.getElementByID("head").ID = "headfixed"
}
}