找到HTML元素和浏览器(或窗口)边之间的距离 [英] Find the distance between HTML element and browser (or window) sides

查看:871
本文介绍了找到HTML元素和浏览器(或窗口)边之间的距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用jQuery查找html元素和浏览器(或窗口)两侧(左侧或顶部)之间的像素距离?

How to find the distance in pixels between html element and one of the browser (or window) sides (left or top) using jQuery?

推荐答案

您可以使用 offset 函数。它为您提供元素相对于文档(左侧,顶部)的位置

You can use the offset function for that. It gives you the element's position relative to the (left,top) of the document:

var offset = $("#target").offset();
display("span is at " + offset.left + "," + offset.top + 
  " of document");

直播范例在我的浏览器中,该示例说明我们定位的跨度为文档的157,47(左侧,顶部)。这是因为我已经为 body 元素应用了一个很大的填充值,并使用了一个间距,上面有一个间隔符,前面有一些文本。

Live example On my browser, that example says that the span we've targeted is at 157,47 (left,top) of the document. This is because I've applied a big padding value to the body element, and used a span with a spacer above it and some text in front of it.

以下是第二个示例,显示文档顶部绝对左侧的段落,显示0,0作为它的位置(并且在稍后显示的跨度从左侧和顶部偏移,129,19在我的浏览器上)。

Here's a second example showing a paragraph at the absolute left,top of the document, showing 0,0 as its position (and also showing a span later on that's offset from both the left and top, 129,19 on my browser).

这篇关于找到HTML元素和浏览器(或窗口)边之间的距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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