用jquery检查div是否有溢出元素 [英] Check with jquery if div has overflowing elements

查看:231
本文介绍了用jquery检查div是否有溢出元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个固定高度的div, overflow:hidden;



我想用jQuery如果div的元素溢出超过div的固定高度。我怎么做到这一点?

解决方案

您实际上不需要任何jQuery来检查是否有溢出发生。使用 element.offsetHeight element.offsetWidth element.scrollHeight 元素。 scrollWidth 您可以确定您的元素的内容是否大于其大小:

  if (element.offsetHeight< element.scrollHeight || 
element.offsetWidth< element.scrollWidth){
//你的元素有溢出
} else {
//你的元素没有溢出
}

请参阅操作示例:小提琴



但是如果你想知道元素内的元素是否可见,那么你需要做更多的计算。在可见性方面,有三个子元素状态:



如果您想要统计半可见项目,它将是您需要的脚本:

  var invisibleItems = []; 
for(var i = 0; i< element.childElementCount; i ++){
if(element.children [i] .offsetTop + element.children [i] .offsetHeight>
element .offsetTop + element.offsetHeight ||
element.children [i] .offsetLeft + element.children [i] .offsetWidth>
element.offsetLeft + element.offsetWidth){

invisibleItems.push(element.children [i]);
}

}

如果你不想要计算半可见性,你可以计算出一点差异。


I have a div with a fixed height and overflow:hidden;

I want to check with jQuery if the div has elements that are overflowing past the fixed height of the div. How can I do this?

解决方案

You actually don't need any jQuery to check if there is an overflow happening or not. Using element.offsetHeight, element.offsetWidth , element.scrollHeight and element.scrollWidth you can determine if your element have content bigger than it's size:

if (element.offsetHeight < element.scrollHeight ||
    element.offsetWidth < element.scrollWidth) {
    // your element have overflow
} else {
    // your element doesn't have overflow
}

See example in action: Fiddle

But if you want to know what element inside your element is visible or not then you need to do more calculation. There is three states for a child element in terms of visibility:

If you want to count semi-visible items it would be the script you need:

var invisibleItems = [];
for(var i=0; i<element.childElementCount; i++){
  if (element.children[i].offsetTop + element.children[i].offsetHeight >
      element.offsetTop + element.offsetHeight ||
      element.children[i].offsetLeft + element.children[i].offsetWidth >
      element.offsetLeft + element.offsetWidth ){

        invisibleItems.push(element.children[i]);
    }

}

And if you don't want to count semi-visible you can calculate with a little difference.

这篇关于用jquery检查div是否有溢出元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆