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

烈酒焚心 提交于 2019-12-23 09:58:12

问题


The tittle really says it all.

Basically i want to detect if this div's height is bigger than window height and do something about it..

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

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


回答1:


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:block elements 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:

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

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

JS Fiddle demo.




回答2:


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



来源:https://stackoverflow.com/questions/7259991/jquery-detect-if-element-height-is-bigger-than-window-height-and-do-something

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