开发者

How to determine if hidden/overflow text is at top or bottom of element

开发者 https://www.devze.com 2022-12-15 22:42 出处:网络
I\'d like to expand on Shog9\'s answer in How to determine from javascript if an html element has overflowing content

I'd like to expand on Shog9's answer in

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

And I'd like to know if the text that is hidden is at the top or at the bottom (or both or none) of the containing ele开发者_运维知识库ment.

What's the best way to go about that?


You can combine scrollLeft and scrollTop with Shog's answer.

Specifically:

// 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;
}


I could not see the forest through the trees. Joel's code snippet var isScrolledDown = el.scrollTop > 0; made me realize how to do it. I used two functions:

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;
}

Haven't tested if it'll work on IE6+ yet, but FF works.

If there are any bugs, please let me know.

0

精彩评论

暂无评论...
验证码 换一张
取 消