我有这个输入元素:

  <input type="text" class="textfield" value="" id="subject" name="subject">

然后我还有一些其他元素,比如其他标签的&<textarea>标签等等。。。

当用户点击<input id=“#subject”>时,页面应该滚动到页面的最后一个元素,并且应该使用一个漂亮的动画(应该滚动到底部而不是顶部)。

页面的最后一项是带有#submit的提交按钮:

<input type="submit" class="submit" id="submit" name="submit" value="Ok, Done.">

动画不应该太快,应该是流畅的。

我正在运行最新的jQuery版本。我宁愿不安装任何插件,而是使用默认的jQuery特性来实现这一点。


当前回答

我设置了一个模块滚动元素npm安装滚动元素。它的工作原理如下:

import { scrollToElement, scrollWindowToElement } from 'scroll-element'

/* scroll the window to your target element, duration and offset optional */
let targetElement = document.getElementById('my-item')
scrollWindowToElement(targetElement)

/* scroll the overflow container element to your target element, duration and offset optional */
let containerElement = document.getElementById('my-container')
let targetElement = document.getElementById('my-item')
scrollToElement(containerElement, targetElement)

在以下SO帖子的帮助下编写:

没有jquery的元素的顶部偏移量不带jquery的滚动条动画

代码如下:

export const scrollToElement = function(containerElement, targetElement, duration, offset) {
  if (duration == null) { duration = 1000 }
  if (offset == null) { offset = 0 }

  let targetOffsetTop = getElementOffset(targetElement).top
  let containerOffsetTop = getElementOffset(containerElement).top
  let scrollTarget = targetOffsetTop + ( containerElement.scrollTop - containerOffsetTop)
  scrollTarget += offset
  scroll(containerElement, scrollTarget, duration)
}

export const scrollWindowToElement = function(targetElement, duration, offset) {
  if (duration == null) { duration = 1000 }
  if (offset == null) { offset = 0 }

  let scrollTarget = getElementOffset(targetElement).top
  scrollTarget += offset
  scrollWindow(scrollTarget, duration)
}

function scroll(containerElement, scrollTarget, duration) {
  let scrollStep = scrollTarget / (duration / 15)
  let interval = setInterval(() => {
    if ( containerElement.scrollTop < scrollTarget ) {
      containerElement.scrollTop += scrollStep
    } else {
      clearInterval(interval)
    }
  },15)
}

function scrollWindow(scrollTarget, duration) {
  let scrollStep = scrollTarget / (duration / 15)
  let interval = setInterval(() => {
    if ( window.scrollY < scrollTarget ) {
      window.scrollBy( 0, scrollStep )
    } else {
      clearInterval(interval)
    }
  },15)
}

function getElementOffset(element) {
  let de = document.documentElement
  let box = element.getBoundingClientRect()
  let top = box.top + window.pageYOffset - de.clientTop
  let left = box.left + window.pageXOffset - de.clientLeft
  return { top: top, left: left }
}

其他回答

要显示整个元素(如果可以使用当前窗口大小):

var element       = $("#some_element");
var elementHeight = element.height();
var windowHeight  = $(window).height();

var offset = Math.min(elementHeight, windowHeight) + element.offset().top;
$('html, body').animate({ scrollTop: offset }, 500);

我就是这样做的。

document.querySelector('scrollHere').scrollIntoView({ behavior: 'smooth' })

适用于任何浏览器。

它可以很容易地包装成函数

function scrollTo(selector) {
    document.querySelector(selector).scrollIntoView({ behavior: 'smooth' })
}

下面是一个工作示例$(“.btn”).click(函数){document.getElementById(“scrollHere”).sollIntoView({behavious:“smooth”})}).btn{margin-bottom:500px;}.middle{显示:块;边距底部:500px;颜色:红色;}<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js“></script><button class=“btn”>向下滚动</button><h1 class=“middle”>看到了吗</h1><div id=“scrollHere”>到达目的地</div>

Docs

我编写了一个通用函数,可以滚动到jQuery对象、CSS选择器或数值。

示例用法:

// scroll to "#target-element":
$.scrollTo("#target-element");

// scroll to 80 pixels above first element with class ".invalid":
$.scrollTo(".invalid", -80);

// scroll a container with id "#my-container" to 300 pixels from its top:
$.scrollTo(300, 0, "slow", "#my-container");

函数的代码:

/**
* Scrolls the container to the target position minus the offset
*
* @param target    - the destination to scroll to, can be a jQuery object
*                    jQuery selector, or numeric position
* @param offset    - the offset in pixels from the target position, e.g.
*                    pass -80 to scroll to 80 pixels above the target
* @param speed     - the scroll speed in milliseconds, or one of the
*                    strings "fast" or "slow". default: 500
* @param container - a jQuery object or selector for the container to
*                    be scrolled. default: "html, body"
*/
jQuery.scrollTo = function (target, offset, speed, container) {

    if (isNaN(target)) {

        if (!(target instanceof jQuery))
            target = $(target);

        target = parseInt(target.offset().top);
    }

    container = container || "html, body";
    if (!(container instanceof jQuery))
        container = $(container);

    speed = speed || 500;
    offset = offset || 0;

    container.animate({
        scrollTop: target + offset
    }, speed);
};

史蒂夫和彼得的解决方案非常有效。

但在某些情况下,您可能必须将该值转换为整数。奇怪的是,$(“…”).offset().top返回的值有时是浮点数。使用:parseInt($(“…”).offset().top)

例如:

$("#button").click(function() {
    $('html, body').animate({
        scrollTop: parseInt($("#elementtoScrollToID").offset().top)
    }, 2000);
});

这是Atharva的回答:https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView.只是想补充一下,如果您的文档在iframe中,您可以在父框架中选择一个元素滚动到视图中:

 $('#element-in-parent-frame', window.parent.document).get(0).scrollIntoView();