如何使用jQuery将元素滚动到视图中?
我有一个HTML文档,其中包含使用< ul>< li>< img ...
的网格格式的图片。浏览器窗口同时具有垂直和放大功能。水平滚动。
I have an HTML document with images in a grid format using <ul><li><img...
. The browser window has both vertical & horizontal scrolling.
问题:
当我点击图片时< img>
,然后如何让整个文档滚动到我刚刚点击的图像 top:20px; left:20px
?
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
?
我在这里浏览了类似帖子...虽然我对JavaScript很新,我想了解这是如何实现的。
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.
既然你想知道它是如何运作的,我会解释一下-by-step。
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
});
这将点击处理程序应用于 id =someImage的图像
。如果您要对所有图像执行此操作,请将'#someImage'
替换为'img'
。
That will apply the click handler to an image with id="someImage"
. If you want to do this to all images, replace '#someImage'
with 'img'
.
现在有实际的滚动代码:
Now for the actual scrolling code:
-
获取图像偏移量(相对于文档):
Get the image offsets (relative to the document):
var offset = $(this).offset(); // Contains .top and .left
从减去20
和左
:
offset.left -= 20;
offset.top -= 20;
现在为< body>
和< html>
:
$('html, body').animate({
scrollTop: offset.top,
scrollLeft: offset.left
});