我有这个输入元素:
<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特性来实现这一点。
在大多数情况下,最好使用插件。认真地我要在这里兜售我的。当然还有其他的。但请检查他们是否真的避免了那些你首先想要插件的陷阱——并不是所有人都这样做。
我写过在其他地方使用插件的原因。简而言之,这里大多数答案的基础是一行
$('html, body').animate( { scrollTop: $target.offset().top }, duration );
是糟糕的用户体验。
动画不会响应用户操作。即使用户单击、轻击或尝试滚动,它也会继续。如果动画的起点接近目标元素,则动画会非常缓慢。如果目标元素位于页面底部附近,则无法滚动到窗口顶部。然后,滚动动画在中间运动时突然停止。
为了处理这些问题(以及其他一些问题),您可以使用我的插件jQuery.scrollable
$( window ).scrollTo( targetPosition );
就这样。当然,还有更多的选择。
关于目标位置,在大多数情况下,$target.offset().top完成任务。但是请注意,返回的值没有考虑html元素上的边框(请参见本演示)。如果你需要目标位置在任何情况下都准确,最好使用
targetPosition = $( window ).scrollTop() + $target[0].getBoundingClientRect().top;
即使在html元素上设置了边框,这也能正常工作。
我设置了一个模块滚动元素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 }
}
如果您对平滑滚动效果不太感兴趣,而只是对滚动到特定元素感兴趣,则不需要使用jQuery函数。Javascript已涵盖您的案例:
https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView
因此,您需要做的就是:$(“selector”).get(0).scrollIntoView();
使用.get(0)是因为我们希望检索JavaScript的DOM元素,而不是JQuery的DOM元素。
更新
现在可以通过滚动选项滚动动画(参见MDN)。您甚至可以控制块的位置。除了Safari,它似乎有很大的支持
$("selector").get(0).scrollIntoView({behavior: 'smooth'});
在找到了让我的代码工作的方法之后,我想我应该把事情弄清楚一点:用于:
$('html, body').animate({
scrollTop: $("#div1").offset().top
}, 2000);
您需要在页面顶部,因为$(“#div1”).offset().top将为您滚动到的不同位置返回不同的数字。如果您已经滚动到顶部,则需要指定确切的pageY值(请参阅此处的pageY定义:https://javascript.info/coordinates).
现在,问题是计算一个元素的pageY值。下面是滚动容器为主体的示例:
function getPageY(id) {
let elem = document.getElementById(id);
let box = elem.getBoundingClientRect();
var body = document.getElementsByTagName("BODY")[0];
return box.top + body.scrollTop; // for window scroll: box.top + window.scrollY;
}
即使您滚动到某个位置,上面的函数也会返回相同的数字。现在,要滚动回该元素:
$("html, body").animate({ scrollTop: getPageY('div1') }, "slow");
非常简单且易于使用的自定义jQuery插件。只需将属性scroll=添加到可单击元素中,并将其值设置为要滚动到的选择器。
像这样:<a scroll=“#product”>单击我</a>。它可以用于任何元素。
(function($){
$.fn.animateScroll = function(){
console.log($('[scroll]'));
$('[scroll]').click(function(){
selector = $($(this).attr('scroll'));
console.log(selector);
console.log(selector.offset().top);
$('html body').animate(
{scrollTop: (selector.offset().top)}, //- $(window).scrollTop()
1000
);
});
}
})(jQuery);
// RUN
jQuery(document).ready(function($) {
$().animateScroll();
});
// IN HTML EXAMPLE
// RUN ONCLICK ON OBJECT WITH ATTRIBUTE SCROLL=".SELECTOR"
// <a scroll="#product">Click To Scroll</a>