jQuery - 检测元素高度是否大于窗口高度并对其进行处理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7259991/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:37:20  来源:igfitidea点击:

jQuery - Detect if element height is bigger than window height and do something about it

jquerywindowheightelementdetect

提问by Joonas

The tittle really says it all.

标题真的说明了一切。

Basically i want to detect if this div's heightis bigger than windowheightand do something about it..

基本上我想检测此divheight比我的大windowheight,做一些事情..

I have done this but i cant get it to work http://jsfiddle.net/dhkCa/3Why wont it work?

我已经这样做了,但我无法让它工作http://jsfiddle.net/dhkCa/3为什么它不起作用?

Edit: Fixed a little error in the css code. Jsfiddle link updated.

编辑:修复了 css 代码中的一个小错误。Jsfiddle 链接已更新。

回答by David says reinstate Monica

The document's contains all the elements within itself, and its height is a sum of the heights of all those elements (all the display:blockelements anyway, plus margin and padding); therefore no contained element can be taller than the document itself. What you need to do is compare the window's height, not the document's:

所述document的包含在其自身内的所有元素,它的高度是所有这些元件的高度(所有的总和display:block反正元素,以及余量和填充); 因此所包含的元素不能比文档本身高。您需要做的是比较window的高度,而不是文档的高度:

var div = $("div").height();
var win = $(window).height();

if (div > win ) {
    $("div").addClass('red');
}

JS Fiddle demo.

JS小提琴演示

回答by Eran Goldin

For an element that has a scroll height that's different than the document's scroll height, you can use element.getBoundingClientRect().height(Docs).

对于滚动高度与文档滚动高度不同的元素,您可以使用element.getBoundingClientRect().height(Docs)