如何使用jQuery将元素滚动到视图中? [英] How do I get an element to scroll into view, using jQuery?

查看:88
本文介绍了如何使用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:


  1. 获取图像偏移量(相对于文档):

  1. 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
    });
    


  • 这篇关于如何使用jQuery将元素滚动到视图中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆