首頁  >  文章  >  web前端  >  如何確定文字內容是否溢出 JavaScript 中的 DIV 元素?

如何確定文字內容是否溢出 JavaScript 中的 DIV 元素?

Susan Sarandon
Susan Sarandon原創
2024-10-26 10:36:03524瀏覽

How can I determine if text content overflows a DIV element in JavaScript?

檢測DIV 元素中的垂直溢出

確定DIV 元素的垂直文字內容是否超出其邊界對於維護介面完整性至關重要。要偵測此溢出,建議比較元素的 rollHeight 和 clientHeight 屬性。

實作:

考慮以下HTML 和CSS 程式碼:

<code class="html"><div id="tempDiv" class="rounded">
  Lorem ipsum dolor sit amet,
  consectetur    adipiscing elit. Phasellus vel quam vestibulum orci blandit laoreet.
</div></code>
<code class="css">div.rounded {
  background-color: #FFF;
  height: 123px;
  width: 200px;
  font-size: 11px;
  overflow: hidden;
}</code>

要偵測溢出,請將下面提供的JavaScript 程式碼插入到頁面中:

<code class="javascript">function GetContainerSize() {
  var container = document.getElementById("tempDiv");
  var message = "The width of the contents with padding: " + container.scrollWidth + "px.\n";
  message += "The height of the contents with padding: " + container.scrollHeight + "px.\n";

  alert(message);
}</code>

執行此函數並出現警報時,比較scrollHeight和clientHeight值將指示是否文字溢位DIV。

更多資源:

有關此主題的更多信息,請參閱以下URL:
http://help.dottoro .com/ljbixkkn. php

以上是如何確定文字內容是否溢出 JavaScript 中的 DIV 元素?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn