javascript textarea scrollTop

时间:2010-01-12 03:00:56

标签: javascript

我试图在用户阅读所有协议后启用复选框。然而,好吧,我已经尝试谷歌搜索无济于事,也困惑。我试图获得scrollTop的“真实”结束,但是由于不同的渲染引擎(gecko,webkit,等等等等),固定值将无效。

这是我学习的一部分,所以请避免使用库发布解决方案。

有什么建议吗?

4 个答案:

答案 0 :(得分:0)

您可以尝试使用textarea的scrollHeight属性并将其与scrollTop进行比较 - 如果它们相等,则用户位于最底层。

答案 1 :(得分:0)

your_textarea.scrollTop + your_textarea.offsetHeight - your_textarea.scrollHeight应该会给你你想要的东西。它可能会偏离几个像素,所以如果它在〜-20范围内,我可能会允许它。例如,我在textarea中粘贴了一大段随机废话并滚动到底部,然后运行该代码,它给了我-2。这是因为底部有时会出现一些空白行。如果没有空行,那么理论上该值应该为0(确保使用===来比较为0。)

理论上。

答案 2 :(得分: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(+ - 几个像素)那么你就在底部..

答案 3 :(得分:0)

这是我的实现,使用阈值(在这种情况下为4)来确定textarea是否滚动到底部(或几乎是底部)。我也包括了计算值的显示。

使用的指标是scrollHeightscrollTop和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的屏幕截图:

On Safari