如何确定隐藏/溢出文本是否位于元素的顶部或底部

时间:2010-01-07 21:25:33

标签: javascript html

我想在

中扩展Shog9的答案

How to determine from javascript if an html element has overflowing content

我想知道隐藏的文本是否位于包含元素的顶部或底部(或两者或没有)。

最好的方法是什么?

2 个答案:

答案 0 :(得分:5)

您可以将scrollLeftscrollTop与Shog的答案合并。

具体做法是:

// Author: Shog9
// Determines if the passed element is overflowing its bounds,
// either vertically or horizontally.
// Will temporarily modify the "overflow" style to detect this
// if necessary.
// Modified to check if the user has scrolled right or down.
function checkOverflow(el)
{
   var curOverflow = el.style.overflow;
   if ( !curOverflow || curOverflow === "visible" )
      el.style.overflow = "hidden";

   var isOverflowing = el.clientWidth < el.scrollWidth 
      || el.clientHeight < el.scrollHeight;

   // check scroll location
   var isScrolledRight = el.scrollLeft > 0;
   var isScrolledDown = el.scrollTop > 0;

   el.style.overflow = curOverflow;

   return isOverflowing;
}

答案 1 :(得分:1)

我无法透过树林看到森林。 Joel的代码片段var isScrolledDown = el.scrollTop > 0;让我意识到如何做到这一点。我使用了两个函数:

function HasTopOverflow(el) {
   return el.scrollTop;
}

function HasBottomOverflow(el) {
   var scrollTop = el.scrollTop,
       clientHeight = el.clientHeight,
       scrollHeight = Math.max(el.scrollHeight, clientHeight);

   return (scrollTop + clientHeight) < scrollHeight;
}

尚未测试它是否可以在IE6 +上运行,但FF有效。

如果有任何错误,请告诉我。