在尝试找到一种可以处理各种情况的解决方案(用于为滚动设置动画的选项、在对象滚动到视图中后在对象周围填充、即使在 iframe 等晦涩的情况下也能工作)之后,我终于编写了自己的解决方案对此。由于在许多其他解决方案失败时它似乎有效,我想我会分享它:
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。