Javascript 如何使用 jQuery 让元素滚动到视图中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4884839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:36:06  来源:igfitidea点击:

How do I get an element to scroll into view, using jQuery?

javascriptjquery

提问by Nasir

I have an HTML document with images in a grid format using <ul><li><img.... The browser window has both vertical & horizontal scrolling.

我有一个 HTML 文档,其中包含使用<ul><li><img.... 浏览器窗口具有垂直和水平滚动。

Question:When I click on an image <img>, how then do I get the whole document to scroll to a position where the image I just clicked on is top:20px; left:20px?

问题:当我单击图像时<img>,如何让整个文档滚动到我刚刚单击的图像所在的位置top:20px; left:20px

I've had a browse on here for similar posts...although I'm quite new to JavaScript, and want to understand how this is achieved for myself.

我在这里浏览过类似的帖子……尽管我对 JavaScript 很陌生,并且想了解我自己是如何实现这一点的。

回答by Andy E

There's a DOM method called scrollIntoView, which is supported by all major browsers, that will align an element with the top/left of the viewport (or as close as possible).

有一种 DOM 方法称为scrollIntoView,所有主要浏览器都支持该方法,它将元素与视口的顶部/左侧对齐(或尽可能靠近)。

$("#myImage")[0].scrollIntoView();

On supported browsers, you can provide options:

在支持的浏览器上,您可以提供以下选项:

$("#myImage")[0].scrollIntoView({
    behavior: "smooth", // or "auto" or "instant"
    block: "start" // or "end"
});

Alternatively, if all the elements have unique IDs, you can just change the hashproperty of the locationobject for back/forward button support:

或者,如果所有元素都有唯一的 ID,您可以更改对象的hash属性以location支持后退/前进按钮:

$(document).delegate("img", function (e) {
    if (e.target.id)
        window.location.hash = e.target.id;
});

After that, just adjust the scrollTop/scrollLeftproperties by -20:

之后,只需将scrollTop/scrollLeft属性调整为-20:

document.body.scrollLeft -= 20;
document.body.scrollTop -= 20;

回答by David Tang

Since you want to know how it works, I'll explain it step-by-step.

既然你想知道它是如何工作的,我会一步一步地解释它。

First you want to bind a function as the image's click handler:

首先,您要绑定一个函数作为图像的点击处理程序:

$('#someImage').click(function () {
    // Code to do scrolling happens here
});

That will apply the click handler to an image with id="someImage". If you want to do this to allimages, replace '#someImage'with 'img'.

这会将点击处理程序应用于带有id="someImage". 如果要对所有图像执行此操作,请替换'#someImage''img'.

Now for the actual scrolling code:

现在是实际的滚动代码:

  1. Get the image offsets (relative to the document):

    var offset = $(this).offset(); // Contains .top and .left
    
  2. Subtract 20 from topand left:

    offset.left -= 20;
    offset.top -= 20;
    
  3. Now animate the scroll-top and scroll-left CSS properties of <body>and <html>:

    $('html, body').animate({
        scrollTop: offset.top,
        scrollLeft: offset.left
    });
    
  1. 获取图像偏移量(相对于文档):

    var offset = $(this).offset(); // Contains .top and .left
    
  2. 减去 20topleft

    offset.left -= 20;
    offset.top -= 20;
    
  3. 现在动画的滚动顶部和滚动左CSS属性<body><html>

    $('html, body').animate({
        scrollTop: offset.top,
        scrollLeft: offset.left
    });
    

回答by Matt Watson

Simplest solution I have seen

我见过的最简单的解决方案

var offset = $("#target-element").offset();
$('html, body').animate({
    scrollTop: offset.top,
    scrollLeft: offset.left
}, 1000);

Tutorial Here

教程在这里

回答by Felix Kling

There are methods to scroll element directly into the view, but if you want to scroll to a point relative from an element, you have to do it manually:

有一些方法可以将元素直接滚动到视图中,但是如果要滚动到元素的相对点,则必须手动进行:

Inside the click handler, get the position of the element relative to the document, subtract 20and use window.scrollTo:

在点击处理程序中,获取元素相对于文档的位置,减去20并使用window.scrollTo

var pos = $(this).offset();
var top = pos.top - 20;
var left = pos.left - 20;
window.scrollTo((left < 0 ? 0 : left), (top < 0 ? 0 : top));

回答by Rob Stevenson-Leggett

Have a look at the jQuery.scrollToplugin. Here's a demo.

看看jQuery.scrollTo插件。这是一个演示

This plugin has a lot of options that go beyond what native scrollIntoViewoffers you. For instance, you can set the scrolling to be smooth, and then set a callback for when the scrolling finishes.

这个插件有很多选项超出了原生 scrollIntoView为您提供的范围。例如,您可以将滚动设置为平滑,然后设置滚动完成时的回调。

You can also have a look at all the JQuery plugins tagged with "scroll".

您还可以查看所有标记为 "scroll" 的 JQuery 插件

回答by Rob

Here's a quick jQuery plugin to map the built in browser functionality nicely:

这是一个快速的 jQuery 插件,可以很好地映射内置的浏览器功能:

$.fn.ensureVisible = function () { $(this).each(function () { $(this)[0].scrollIntoView(); }); };

...

$('.my-elements').ensureVisible();

回答by Tone ?koda

After trial and error I came up with this function, works with iframe too.

经过反复试验,我想出了这个功能,也适用于 iframe。

function bringElIntoView(el) {    
    var elOffset = el.offset();
    var $window = $(window);
    var windowScrollBottom = $window.scrollTop() + $window.height();
    var scrollToPos = -1;
    if (elOffset.top < $window.scrollTop()) // element is hidden in the top
        scrollToPos = elOffset.top;
    else if (elOffset.top + el.height() > windowScrollBottom) // element is hidden in the bottom
        scrollToPos = $window.scrollTop() + (elOffset.top + el.height() - windowScrollBottom);
    if (scrollToPos !== -1)
        $('html, body').animate({ scrollTop: scrollToPos });
}

回答by wp student

Just a tip. Works on firefox only

只是一个提示。仅适用于 Firefox

Element.scrollIntoView();

元素.scrollIntoView();

回答by xeo

My UI has a vertical scrolling list of thumbs within a thumbbar The goal was to make the current thumb right in the center of the thumbbar. I started from the approved answer, but found that there were a few tweaks to truly center the current thumb. hope this helps someone else.

我的用户界面在拇指栏中有一个拇指的垂直滚动列表目标是使当前拇指位于拇指栏的中心。我从批准的答案开始,但发现有一些调整可以真正使当前拇指居中。希望这对其他人有帮助。

markup:

标记:

<ul id='thumbbar'>
    <li id='thumbbar-123'></li>
    <li id='thumbbar-124'></li>
    <li id='thumbbar-125'></li>
</ul>

jquery:

查询:

// scroll the current thumb bar thumb into view
heightbar   = $('#thumbbar').height();
heightthumb = $('#thumbbar-' + pageid).height();
offsetbar   = $('#thumbbar').scrollTop();


$('#thumbbar').animate({
    scrollTop: offsetthumb.top - heightbar / 2 - offsetbar - 20
});

回答by Shiva Kumar P

Simple 2 steps for scrolling down to end or bottom.

向下滚动到结尾或底部的简单 2 个步骤。

Step1: get the full height of scrollable(conversation) div.

Step1:获取可滚动(对话)div的完整高度。

Step2: apply scrollTop on that scrollable(conversation) div using the value obtained in step1.

步骤 2:使用步骤 1 中获得的值在该可滚动(对话)div 上应用 scrollTop。

var fullHeight = $('#conversation')[0].scrollHeight;

$('#conversation').scrollTop(fullHeight);

Above steps must be applied for every append on the conversation div.

以上步骤必须应用于对话 div 上的每个附加。