【问题标题】:Scroll to next div on click, from current location单击时从当前位置滚动到下一个 div
【发布时间】:2015-12-22 05:27:37
【问题描述】:

在我当前从一个 div 滚动到另一个 div 的解决方案中,我支持 previousnext

这可以通过保存上次滚动到的 div 的索引来确定下一个滚动到的位置。但是,当用户使用滚轮滚动时,这会中断。我想知道是否有办法计算哪个 div 最接近窗口顶部,然后确定下一个滚动到哪个索引。

这反过来会消除我遇到的问题。

使用我当前的解决方案测试错误:


  1. 转到 jsfiddle 链接
  2. 单击向下箭头两次。它应该从一个 div 滚动到下一个。
  3. 接下来,使用鼠标滚轮向下滚动页面的 3/4。
  4. 现在再次点击向下箭头。您会看到它会带您回到上次离开时​​的顶峰。

http://jsfiddle.net/JokerMartini/yj9pvz2a/1/

var curr_el_index = 0;
var els_length = $(".section").length;

    $('.btnNext').click(function () {
        curr_el_index++;
        if (curr_el_index >= els_length) curr_el_index = 0;
        $("html, body").animate({
            scrollTop: $(".section").eq(curr_el_index).offset().top - 20
        }, 700);
    });

    $('.btnPrev').click(function () {
        curr_el_index--;
        if (curr_el_index < 0) curr_el_index = els_length - 1;
        $("html, body").animate({
            scrollTop: $(".section").eq(curr_el_index).offset().top - 20
        }, 700);
    });

解决方案更新: http://jsfiddle.net/JokerMartini/82wo9e3c/1/

【问题讨论】:

    标签: jquery html css scroll


    【解决方案1】:

    您可以使用 jquery 偏移量 (http://api.jquery.com/offset/) 检索元素相对于文档的当前偏移量。所以你可以使用这样的东西:

    function getTopElement(elements){
      var topEl;
      $.each(elements, function(index,el){
        if(!topEl || topEl.offset().top < el.offset().top){
          topEl = el;
        }
     });
    
      return topEl;
    }
    

    【讨论】:

    • 如何在现有代码中实现?
    【解决方案2】:

    根据 this answer, 有一种方法可以计算 div 与视口顶部的距离,具体如下:

    ($element.offset().top - $(window).scrollTop())
    

    所以,你只需要找到具有最小正值的那个:

    var closest_to_top = $('.section').toArray().reduce(function(curr, section) {
        var bottom = $(section).offset().top + $(section).height()
        var distance = (bottom - $(window).scrollTop())
        if (distance < 0) return curr
        return distance > curr.distance ? curr : {
            distance : distance,
            section : section
        }
    }, {section:null, distance:+Infinity}).section
    

    这是底部低于视口顶部的最高部分。如果需要部分的顶部,请删除 +$(section).height()

    【讨论】:

      【解决方案3】:

      尝试添加它来处理页面滚动。演示:http://jsfiddle.net/yj9pvz2a/2/

      var section_height = $(".section").height() + 80; //80 margins
      
      $(window).on('scroll', function() {
          curr_el_index = Math.floor($(window).scrollTop() / section_height);
      });
      

      解释:所以您在代码中遇到的是,当用户不使用您的导航滚动到不同部分时,curr_el_index 保持不变。这个$(window).scroll() 函数考虑到滚动不是来自您的导航按钮。

      功能:在按钮滚动时,它获取窗口的滚动高度并将其除以部分的滚动高度并将其向下舍入到最接近的整数并将当前索引部分设置为该数字。

      【讨论】:

      • 如果您同时滚动多个 div 元素,这可能会失败。
      • 直接从 A 滚动到 J,然后单击向上箭头。跳过 I 直接进入 H。但是这个解决方案几乎适用于这里的所有情况。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-19
      • 1970-01-01
      • 1970-01-01
      • 2014-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多