检测textarea何时滚动到底部

时间:2013-10-28 02:49:58

标签: jquery css

有没有办法衡量用户何时滚动到元素的底部?我知道jQuery可以访问元素的scrollTop(),但即使将它与元素的高度相结合,我也无法计算元素何时滚动到最底部位置。我想这样做,所以当在textarea中滚动时,我可以防止文档的主体在达到textarea的“滚动底部”时滚动。

JSBIN

2 个答案:

答案 0 :(得分:11)

以下是您要找的内容: http://jsfiddle.net/BW8LT/1/

$('textarea#mytextarea').on('scroll', function() {
    var offset = 200; // height of textarea

    if (this.scrollHeight <= (this.scrollTop+offset)) {
        console.log('end of textarea!');
    }
});

编辑1 通过隐藏溢出来禁用滚动

$('textarea#mytextarea').on('scroll', function() {
    var offset = 200; // height of textarea

    if (this.scrollHeight <= (this.scrollTop+offset)) {
        // hide the overflow (=> disable scrolling) when the end is reached
        $('body').css('overflow', 'hidden');
    }
});

// re-enable scrolling on mouseout
$('textarea#mytextarea').on('mouseout', function() {
    $('body').css('overflow', 'scroll');
});

只需将textarea.scrollHeighttextarea.scrollTop进行比较。

滚动时查看控制台。希望有所帮助!

答案 1 :(得分:2)

这是我的解决方案(JSBin):

$('textarea').scroll(function() {
  if ($(this).scrollTop() + $(this).height() >= $(this)[0].scrollHeight - 4) {
    alert("You scrolled to the bottom!");
  }
});
相关问题