这里的每个答案要么似乎已经过时并且不再适用于现代版本的 jQuery(可能是由于 position() 和 offset() 函数的变化),要么在我需要它们的情况下工作太有限。例如,如果您的代码在 iframe 中,上述答案似乎都不起作用。
我注意到的最重要的事情之一是它们都只使用了容器对象的正常高度,只要整个容器对象在窗口中可见,它就可以正常工作,但是当你的容器对象是 html 对象本身时并且高度远远低于显示的高度,代码的向下滚动部分不再起作用。相反,该算法需要使用对象在屏幕上的可见高度才能正常工作(请参阅Get the visible height of a div with jQuery)。
我最终编写了自己的解决方案,该解决方案看起来更加强大并且适用于更多情况:
function scrollIntoViewIfNeeded($target, options) {
var options = options ? options : {},
$win = $($target[0].ownerDocument.defaultView), //get the window object of the $target, don't use "window" because the element could possibly be in a different iframe than the one calling the function
$container = options.$container ? options.$container : $win,
padding = options.padding ? options.padding : 20,
elemTop = $target.offset().top,
elemHeight = $target.outerHeight(),
containerTop = $container.scrollTop(),
//Everything past this point is used only to get the container's visible height, which is needed to do this accurately
containerHeight = $container.outerHeight(),
winTop = $win.scrollTop(),
winBot = winTop + $win.height(),
containerVisibleTop = containerTop < winTop ? winTop : containerTop,
containerVisibleBottom = containerTop + containerHeight > winBot ? winBot : containerTop + containerHeight,
containerVisibleHeight = containerVisibleBottom - containerVisibleTop;
if (elemTop < containerTop) {
//scroll up
if (options.instant) {
$container.scrollTop(elemTop - padding);
} else {
$container.animate({scrollTop: elemTop - padding}, options.animationOptions);
}
} else if (elemTop + elemHeight > containerTop + containerVisibleHeight) {
//scroll down
if (options.instant) {
$container.scrollTop(elemTop + elemHeight - containerVisibleHeight + padding);
} else {
$container.animate({scrollTop: elemTop + elemHeight - containerVisibleHeight + padding}, options.animationOptions);
}
}
}
$target 是一个 jQuery 对象,其中包含您希望在需要时滚动到视图中的对象。
options(可选)可以在对象中包含以下选项:
options.$container - 一个 jQuery 对象,指向 $target 的包含元素(换句话说,DOM 中带有滚动条的元素)。默认为包含 $target 元素的窗口,并且足够智能以选择 iframe 窗口。请记住在属性名称中包含 $。
options.padding - 当对象滚动到视图中时添加到对象上方或下方的填充(以像素为单位)。这样它就不会靠在窗户的边缘。默认为 20。
options.instant - 如果设置为 true,则不会使用 jQuery animate,并且滚动条会立即弹出到正确的位置。默认为 false。
options.animationOptions - 您希望传递给 jQuery animate 函数的任何 jQuery 选项(请参阅http://api.jquery.com/animate/)。这样,您可以更改动画的持续时间或在滚动完成时执行回调函数。这仅在 options.instant 设置为 false 时有效。如果您需要即时动画但需要回调,请设置options.animationOptions.duration = 0 而不是使用options.instant = true。