Execute function if document is taller than viewport

坚强是说给别人听的谎言 提交于 2019-12-10 19:17:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!