• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

可滚动面板捕捉到滚动上的元素

用户头像
it1352
帮助1

问题说明

当用户滚动时,可滚动div中是否有一种方法可以捕捉到元素。

Is there a way inside a scrollable div to snap to elements as the user scrolls.

例如,如果我们有CSS,例如

For example if we have CSS such as

.container {
    height: 300px;
    width: 200px;
    overflow: auto
}
li {
    height: 40px;
    width: 100 % ;
}

和HTML as

<div class="container">
    <li>
        test
    </li>
    <li>
        test
    </li>
    <li>
        test
    </li>
    <li>
        test
    </li>
    <li>
        test
    </li>
    <li>
        test
    </li>
    <li>
        test
    </li>
    <li>
        test
    </li>
    <li>
        test
    </li>
    <li>
        test
    </li>
    <li>
        test
    </li>
    <li>
        test
    </li>
    <li>
        test
    </li>
</div>

因此容器应该有一个垂直滚动条。当用户滚动时我希望它能够在它们停止滚动时最终滚动位置将容器滚动位置捕捉到所示的最近的div。这可能很难,因为像safari这样的浏览器也会提供动力,因此它必须是滚动结束时的事件。

So from that the container should have a vertical scroll bar. When the user scrolls I would like it so that when they stop scrolling the final scroll position snaps the container scroll position to the nearest div at shown. This might be difficult as browsers like safari offer momentum as well, so it would have to be an event on scroll end.

任何想法,如果这是可能的,以及如何。

Any ideas if this is possible, and how.

Marvelous

Marvellous

正确答案

#1

您可以使用setTimeout。这应该工作

You can use setTimeout. This should work

var snap_timer;
var scroll_from_mouse = true;

function snapList(){
  var snapped = false;
  var i = 0;
  while(!snapped && i < $('.container li').size()){
    var itop = $('.container li').eq(i).position().top;
    var iheight = $('.container li').eq(i).outerHeight();
    if(itop < iheight && itop > 0){ 
      scroll_from_mouse = false;
      snapped = true;
      var new_scroll_top = 0;
      if(iheight - itop > iheight / 2)
        new_scroll_top = $('.container').scrollTop()   itop;
      else if(i > 1)
        new_scroll_top = $('.container').scrollTop() - ($('.container li').eq(i-1).outerHeight() - itop);
      else
        new_scroll_top = 0;
      $('.container').scrollTop(new_scroll_top);
    }
    i  ;
  }
};

$(function(){
  $('.container').scroll(function(){
    clearTimeout(snap_timer);
    if(scroll_from_mouse) snap_timer = setTimeout(snapList, 200);
    scroll_from_mouse = true;
  });
});

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcakfbk
系列文章
更多 icon
同类精品
更多 icon
继续加载