簡體   English   中英

在 div 中檢測到垂直溢出時,有沒有辦法觸發事件?

[英]is there a way to fire a event when vertical overflow is detected in a div?

我的頁面的 html 如下所示:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>demo</title>
    <style type="text/css">
        div.page {
            position: relative;
            background-color: #F2F2F2;
            box-shadow: 0 5px 10px rgba(0, 0, 0, 0.5);
            width: 794px;
            height: 1123px;
            margin-left: auto;
            margin-right: auto;
            margin-top: 30px;
            margin-bottom: 30px;
            overflow: hidden;
        }
    </style>
</head>
<body>
<div id="form">
    <div id="page-1" class="page"></div>
    <div id="page-2" class="page"></div>
</div>
</body>
</html>

它模擬Word一樣的分頁樣式,將內容動態插入到每個頁面div中。 如果頁面div中的內容溢出,我想將溢出的內容放入下一頁div(如果下一頁不存在,則創建一個新div)。 所以我想知道是否有辦法讓頁面 div 在內容溢出時觸發事件,這樣我就可以反向循環內容元素來決定哪些元素應該放入下一個頁面 div。

任何朝正確方向的推動都將是巨大的幫助! 謝謝你。

您可以獲得嵌套 DIV 的 clientHeight,該 DIV 是溢出 DIV 的子級。 換句話說...

<div style="overflow:auto">
   <div id="actualContent" style="overflow:visible">
your content here
   </div>

</div>

測量內部 div 的 clientHeight 並將其與外部 div 的 clientHeight 進行比較。

我會使用一個額外的 div,該 div 位於屏幕外並且與您的頁面 div 具有完全相同的內容(您應該保持更新)。 唯一的區別是額外的 div 沒有“溢出:隱藏”。

現在,檢查兩個div的高度是否有差異,如果有,就是內容溢出了!

讓我們清楚地了解以下定義。

查看 - 可視區域或包含內容的框

content - 溢出的內容。

檢測溢出檢查視圖之間的差異。 offsetHeight和內容。 offsetHeight和您溢出的內容是這個減去值。

我有這個問題的解決方案。 但它僅適用於內聯 CSS。

<!DOCTYPE html
<html>
<head>
<style>
#overflowTest {
  background: #4CAF50;
  color: white;
  padding: 15px;
  width: 50%;
  height: 100px;
  border: 1px solid #ccc;
}
</style>
</head>
<body>

<h2>CSS Overflow</h2>
<p>The overflow property controls what happens to content that is too big to fit into an area.</p>

<div id="overflowTest" style="overflow: scroll">This text is really long and the height of its container is only 100 pixels. Therefore, a scrollbar is added to help the reader to scroll the content. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</div>
<script>
function overflowDetector(x){return x.style.overflow;}

var overflow = overflowDetector(document.querySelector("#overflowTest"));

if(overflow === "scroll"){
    alert("overflow : scroll");
}
else{
    alert("overflow : "+overflow);
}
</script>

</body>
</html>

是的。 使用“溢出”事件。

window.addEventListener ("overflow", yourFunction, false);

您可能必須取消 overflow:hidden 並將其設置為overlflow:auto(例如)才能觸發,但是一旦觸發,您可以將溢出設置回隱藏並執行其余的內容拆分例程。

我相信在 Chrome 和 Safari 中也有類似的事件:“overflowchanged”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM