代码之家  ›  专栏  ›  技术社区  ›  slolife

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

  •  2
  • slolife  · 技术社区  · 15 年前

    我想详细介绍一下Shog9的回答

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

    最好的办法是什么?

    2 回复  |  直到 8 年前
        1
  •  5
  •   Joel    15 年前

    你可以合并 scrollLeft scrollTop 用肖格的回答。

    // 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;
    }
    
        2
  •  1
  •   slolife    15 年前

    透过树林我看不见森林。乔尔的代码片段 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可以工作。