使用jQuery滚动到一个元素

cam*_*aca 14 html javascript jquery

我需要页面滚动才能看到元素.

我试过的选项:

  • jQuery scrollTo:问题是页面滚动使元素位于顶部(或者至少它试图这样做,就像它的工作原理一样:<a name="xyz">/ <a href="#xyz">).我想要的是最小滚动量,以便整个元素可见(并且,如果元素太高,就像那里的锚一样工作).

  • scrollIntoView:太糟糕了,我想让它顺利滚动(比如$.scrollTo($('#id1'), 'fast');).此外,它似乎也没有做我想要的.

Orb*_*ing 19

你需要做的是找出元素,顶部和底部的页面中的位置(和左/右如果你正在考虑横向滚动).然后识别窗口视口的当前位置,窗口的scrollTop的然后应该动画任何值将带给对方只是来查看.

我刚刚在这个编辑器中敲了下来,所以它没有经过测试,但会给你一个插件的一般想法.

更新 - 显示适用于OP的版本,以及更流畅的版本

jQuery.fn.scrollMinimal = function(smooth) {
  var cTop = this.offset().top;
  var cHeight = this.outerHeight(true);
  var windowTop = $(window).scrollTop();
  var visibleHeight = $(window).height();

  if (cTop < windowTop) {
    if (smooth) {
      $('body').animate({'scrollTop': cTop}, 'slow', 'swing');
    } else {
      $(window).scrollTop(cTop);
    }
  } else if (cTop + cHeight > windowTop + visibleHeight) {
    if (smooth) {
      $('body').animate({'scrollTop': cTop - visibleHeight + cHeight}, 'slow', 'swing');
    } else {
      $(window).scrollTop(cTop - visibleHeight + cHeight);
    }
  }
};

$('#item').scrollMinimal();
Run Code Online (Sandbox Code Playgroud)


Rob*_*nik 15

有一个插件可以满足您的需求

我不想从博客文章中复制代码,因为它可能会过时(由于升级).但无论如何.您可以.scrollintoview()博客文章中找到有关jQuery插件的所有详细信息和代码.

用法

scrollTo()必须提供可滚动元素的插件相反,此插件仅要求您提供要滚动到视图中的元素.插件找到最近的可滚动祖先(带滚动条)并滚动到带动画的元素,因此用户不会在页面中松开它们的位置.

好处是,如果元素已经在可滚动祖先的可见边界内,它将不会滚动任何内容.

 $("ElementSelector").scrollintoview();
Run Code Online (Sandbox Code Playgroud)

这是大部分时间.但是,如果您需要设置一些其他设置,您可以更改并提供自定义行为:

scrollintoview: function (options) {
    /// <summary>Scrolls the first element in the set into view by scrolling its closest scrollable parent.</summary>
    /// <param name="options" type="Object">Additional options that can configure scrolling:
    ///        duration (default: "fast") - jQuery animation speed (can be a duration string or number of milliseconds)
    ///        direction (default: "both") - select possible scrollings ("vertical" or "y", "horizontal" or "x", "both")
    ///        complete (default: none) - a function to call when scrolling completes (called in context of the DOM element being scrolled)
    /// </param>
    /// <return type="jQuery">Returns the same jQuery set that this function was run  on.</return>
Run Code Online (Sandbox Code Playgroud)

  • +1比接受的答案中的代码好多了. (2认同)
  • @Orbling:对不起.我的海湾.通过浏览你的代码我虽然你使用`scrollTo`插件而不是构建在jQuery`rollTop`函数中.对于那个很抱歉.我不觉得被打倒了.没有.因为我看到了新的评论,所以让我检查一下.:)无论如何伟大的代码. (2认同)