【问题标题】:Alerting user when div has been scrolled into view当 div 滚动到视图中时提醒用户
【发布时间】:2015-09-25 18:52:07
【问题描述】:

我试图在用户向下滚动到特定 div 时执行功能/提醒用户,然后他们滚动到页面底部。当用户滚动到底部并返回到顶部时,我能够发出警报,但不确定如何指定用户何时滚动到折叠下方(到中间部分)。到目前为止,我有以下内容:

HTML

<div class="container top">TOP</div>
<div class="container middle">Middle</div>
<div class="container bottom">Bottom</div>

jQuery

$(function () {
    var $win = $(window);

    $win.scroll(function () {
        if ($win.scrollTop() == 0) {
            alert("USER SCROLLED TO TOP");
        } else if ($win.height() + $win.scrollTop() == $(document).height()) {
            alert("USER SCROLLED TO BOTTOM");
        }
    });
});

JSFIDDLE:LINK

【问题讨论】:

标签: javascript jquery


【解决方案1】:

https://jsfiddle.net/xsLx9ojs/1/

我将 id 添加到 html div:

<div id="top" class="container top">TOP</div>
<div id="bottom" class="container bottom">BOTTOM</div>

然后我添加一个条件来检测当用户滚动时底部 div 何时出现在用户的屏幕中:

$(function () {

      var $win = $(window);

      $win.scroll(function () {
          if ($win.scrollTop() == 0) {
              console.log("USER SCROLLED TO TOP");
          } else if ($win.height() + $win.scrollTop() >= $('#top').height() - 50 
                    && $win.height() + $win.scrollTop() <= $('#top').height() + 50) {
              console.log("TRANSITION BETWEEN THE TWO DIVS");
          } else if ($win.height() + $win.scrollTop() == $(document).height()) {
              console.log("USER SCROLLED TO BOTTOM");
          }
      });

  });

滚动检测并不是鼠标滚轮那样小“跳跃”的精确原因。所以我添加了一个 100px 的容差。如果我是你,我会用一个布尔值来改进这个东西,它检测是否已经给出了底部 div 的警报,所以这个函数不会在每次滚动时触发,如下所示:

    [...]
    if ($win.scrollTop() == 0) {
        //top reached
    } else if ($win.height() + $win.scrollTop() >= $('#top').height()) {
        //alert! bottom div appeared while scrolling bottom!
        //deal with this with a boolean
    } else if ($win.scrollTop() <= $('#top').height()) {
        //alert! bottom div disappeared while scrolling top!
        //deal with this with a boolean
    } else if ($win.height() + $win.scrollTop() == $(document).height()) {
        //bottom reached
    }
    [...]

【讨论】:

    【解决方案2】:

    部分问题在于$(document).height() 的值可能永远无法通过滚动获得,因为页面中的元素会影响实际文档高度与用户能够滚动的高度。

    你可以像这样找到底部容器的位置

    $('.bottom').position();

    但这只会给你元素在其父元素中的位置。然后,您需要计算相对于每个父母和祖父母的偏移量(如果适用)。

    同样,您可以查看getBoundingClientRect function

    $('.bottom')[0].getBoundingClientRect();
    

    查看库Waypoints 以查看“现成”版本。

    更新 1: 对于您的 JSFiddle 示例,请记住,Waypoints 需要有一个元素击中窗口顶部才能触发(这是默认设置 - 您可以使用 offset 调整此行为)。

    See my JSFiddle here where 根据您的 JSFiddle,我已将每个 div 放大以允许窗口滚动通过。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-06
    • 1970-01-01
    相关资源
    最近更新 更多