Home  >  Article  >  Web Front-end  >  Example of usage of offset() method in jQuery_jquery

Example of usage of offset() method in jQuery_jquery

WBOY
WBOYOriginal
2016-05-16 16:20:001146browse

The example in this article describes the usage of the offset() method in jQuery. Share it with everyone for your reference. The specific analysis is as follows:

This method returns or sets the offset of the matched element relative to the document object.

Grammar structure 1:

Copy code The code is as follows:
$(selector).offset()

Get the relative offset of the matching element in the current document.
The returned object contains two integer properties: top and left.
This method only works on visible elements.

Example code:

Copy code The code is as follows:






offset() function-Script Home











The above code can pop up the offset of the sub-div relative to the document.

Grammar structure 2:

Copy code The code is as follows:
$(selector).offset(value)

Set the coordinates of the matching element relative to the document object.
The offset() method allows us to reset the position of the element. The position of this element is relative to the document object.
If the original position style attribute of the object is static, it will be changed to relative to implement relocation.

Parameter list:

参数 描述
value 规定以像素计的 top 和 left 坐标。
可能的值:
1.值对,比如 {top:200,left:10}。
2.带有top和left 属性的对象。

实例代码:

复制代码 代码如下:






offset()函数-脚本之家






 





以上代码可以设置div相对于document的偏移量。

语法结构三:

使用函数的返回值来设置偏移坐标:

复制代码 代码如下:
$(selector).offset(function(index,oldoffset))

参数列表:

参数 描述
function(index,oldvalue) 规定返回被选元素新偏移坐标的函数:
index - 可选。元素的索引。
oldvalue - 可选。当前坐标。

实例代码:

复制代码 代码如下:






offset()函数-脚本之家






 





以上代码同样可以设置元素的偏移,不过值是通过函数返回。

希望本文所述对大家的jQuery程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn