小编典典

检查元素的内容是否溢出?

javascript

检测元素是否已溢出的最简单方法是什么?

我的用例是,我想限制某个内容框的高度为300px。如果内部内容比这更高,我会溢出来。但是,如果溢出,我想显示一个“更多”按钮,但是如果不是,我不想显示该按钮。

有没有检测溢出的简便方法,还是有更好的方法?


阅读 237

收藏
2020-05-01

共1个答案

小编典典

如果只想显示更多内容的标识符,则可以使用纯CSS来实现。我为此使用纯滚动阴影。诀窍是使用background-attachment: local;。您的CSS看起来像这样:

.scrollbox {

  overflow: auto;

  width: 200px;

  max-height: 200px;

  margin: 50px auto;



  background:

    /* Shadow covers */

    linear-gradient(white 30%, rgba(255,255,255,0)),

    linear-gradient(rgba(255,255,255,0), white 70%) 0 100%,



    /* Shadows */

    radial-gradient(50% 0, farthest-side, rgba(0,0,0,.2), rgba(0,0,0,0)),

    radial-gradient(50% 100%,farthest-side, rgba(0,0,0,.2), rgba(0,0,0,0)) 0 100%;

  background:

    /* Shadow covers */

    linear-gradient(white 30%, rgba(255,255,255,0)),

    linear-gradient(rgba(255,255,255,0), white 70%) 0 100%,



    /* Shadows */

    radial-gradient(farthest-side at 50% 0, rgba(0,0,0,.2), rgba(0,0,0,0)),

    radial-gradient(farthest-side at 50% 100%, rgba(0,0,0,.2), rgba(0,0,0,0)) 0 100%;

  background-repeat: no-repeat;

  background-color: white;

  background-size: 100% 40px, 100% 40px, 100% 14px, 100% 14px;



  /* Opera doesn't support this in the shorthand */

  background-attachment: local, local, scroll, scroll;

}


<div class="scrollbox">

  <ul>

    <li>Not enough content to scroll</li>

    <li>2</li>

    <li>3</li>

    <li>4</li>

    <li>5</li>

  </ul>

</div>





<div class="scrollbox">

  <ul>

    <li>Ah! Scroll below!</li>

    <li>2</li>

    <li>3</li>

    <li>4</li>

    <li>5</li>

    <li>6</li>

    <li>7</li>

    <li>8</li>

    <li>9</li>

    <li>10</li>

    <li>1</li>

    <li>2</li>

    <li>3</li>

    <li>4</li>

    <li>5</li>

    <li>6</li>

    <li>7</li>

    <li>8</li>

    <li>The end!</li>

    <li>No shadow there.</li>

  </ul>

</div>
2020-05-01