问题
This is some quite strange behaviour I experience. I want to execute a function only when the document is taller than the viewport (i.e. it overflows it and a scrollbar appears). I use this code:
var docH = $("document").height(),
viewPortH = $("window").height();
if (docH > viewPortH) {
// execute functions
}
But nothing happens and console returns:
Uncaught TypeError: Cannot read property 'parent' of null
Does anyone know what the problem is/what code I should use to see whether the document is taller than the viewport?
回答1:
document
and window
are objects not selectors.
var docH = $(document).height(),
viewPortH = $(window).height();
回答2:
You don't need the quotes around document
and window
.
var docH = $(document).height(),
viewPortH = $(window).height();
if (docH > viewPortH) {
// execute functions
}
Example fiddle
With the quotes in place jQuery was actually looking for elements like <document />
and <window />
in the DOM.
回答3:
try using document and window like this:
var docH = $(document).height(),
viewPortH = $(window).height();
来源:https://stackoverflow.com/questions/14231568/execute-function-if-document-is-taller-than-viewport