我有这个输入元素:

  <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特性来实现这一点。


当前回答

截至2019年的更新答案:

$('body').animate({
    scrollTop: $('#subject').offset().top - $('body').offset().top + $('body').scrollTop()
}, 'fast');

其他回答

使用此解决方案,您不需要任何插件,并且除了在关闭</body>标记之前放置脚本外,不需要进行任何设置。

$("a[href^='#']").on("click", function(e) {
  $("html, body").animate({
    scrollTop: $($(this).attr("href")).offset().top
  }, 1000);
  return false;
});

if ($(window.location.hash).length > 1) {
  $("html, body").animate({
    scrollTop: $(window.location.hash).offset().top
  }, 1000);
}

加载时,如果地址中有哈希,我们会滚动到它。

而且,每当您单击带有href哈希的链接(例如#top)时,我们都会滚动到它。

##编辑2020

如果你想要一个纯JavaScript的解决方案:你可以使用类似的方法:

var _scrollToElement = function (selector) {
  try {
    document.querySelector(selector).scrollIntoView({ behavior: 'smooth' });
  } catch (e) {
    console.warn(e);
  }
}

var _scrollToHashesInHrefs = function () {
  document.querySelectorAll("a[href^='#']").forEach(function (el) {
    el.addEventListener('click', function (e) {
      _scrollToElement(el.getAttribute('href'));
      return false;
    })
  })
  if (window.location.hash) {
    _scrollToElement(window.location.hash);
  }
}

_scrollToHashesInHrefs();

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

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

例如:

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

jQuery(document).ready(函数($){$('a[href^=“#”]').bind('click.s平滑滚动',函数(e){e.预防违约();var目标=this.hash,$target=$(目标);$('html,body').stop().animate({“scrollTop”:$target.offset().top-40},900,'摆动',函数(){window.location.hash=目标;} );} );} );<script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js“></script><ul role=“tablist”><li class=“active”id=“p1”><a href=“#pane1”role=“tab”>第1节</a></li><li id=“p2”><a href=“#pane2”role=“tab”>第2节</a></li><li id=“p3”><a href=“#pane3”role=“tab”>第3节</a></li></ul><div id=“pane1”></div><div id=“pane2”></div><div id=“pane3”></div>

这在没有jQuery的情况下是可以实现的:

document.getElementById("element-id").scrollIntoView();

我设置了一个模块滚动元素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 }
}