[英]javascript textarea scrollTop
一旦用戶閱讀所有協議,我將嘗試啟用復選框。 但是,嗯,我嘗試了無濟於事的谷歌搜索,並且感到困惑。 我正在嘗試獲得scrollTop的“真實”結尾,但是由於使用了不同的呈現引擎(壁虎,webkit,等等),固定值將不起作用。
這是我學習的一部分,因此請避免在庫中發布解決方案。
有什么建議么?
您可以嘗試使用textarea的scrollHeight
屬性,並將其與scrollTop
進行比較-如果相等,則用戶位於最底端。
your_textarea.scrollTop + your_textarea.offsetHeight - your_textarea.scrollHeight
應該會為您提供所需的內容。 它可能會偏離幾個像素,所以如果它在〜-20范圍內,我可能會允許它。 例如,我在文本區域中粘貼了大量冗長的隨機廢話序列,然后滾動到底部,然后運行該代碼,結果為-2。 這是因為有時在底部有一些空白行。 如果沒有空行,則理論上該值應為0(請確保使用===
與0進行比較。)
理論上。
找到滾動容器的高度(假設它具有id="scroll"
)
var container_real_height = document.getElementById('scroll').offsetHeight
現在計算
var container_content_height = document.getElementById('scroll').scrollHeight;
var container_scroll_amount = document.getElementById('scroll').scrollTop;
如果container_content_height = container_scroll_amount + container_real_height(+-幾個像素),那么您位於底部。
這是我使用閾值(在這種情況下為4)確定文本區域是否滾動到底部(或幾乎底部)的實現。 我還包括了計算值的顯示。
使用的指標是scrollHeight
, scrollTop
和jQuery的元素height()
。
閾值“ 4”適用於IE8,Webkit瀏覽器和FF3.5。 FF3.5和Safari(Windows)可以一直為0。
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" >
$(function() {
$('#cb').hide(); //hide checkbox
var scrollThreshold = 4; //threshold value
var ta0 = $("#ta");
var ta = $("#ta")[0];
$("#ta").scroll(function(){
var p = ta.scrollHeight - (ta.scrollTop + ta0.height());
$('#pos').val(ta.scrollHeight + ' - (' + ta.scrollTop + ' + ' + ta0.height() + ') = ' + p);
if(p <= scrollThreshold) //if scroll value falls within threshold
$('#cb').show(); //show checkbox
}
);
});
</script>
</head>
<body>
<textarea id="ta" style="width: 200px; height: 100px;">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
when an unknown printer took a galley of type and scrambled it to make a type specimen book.</textarea>
<br />
<input type="text" id="pos" />
<input type="checkbox" id="cb" />
</body>
</html>
這是Safari的屏幕截圖:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.