Home Web Front-end JS Tutorial Detailed explanation of jQuery position() function and application of position function in jQuery_jquery

Detailed explanation of jQuery position() function and application of position function in jQuery_jquery

May 16, 2016 pm 03:25 PM

The

position() function is used to return the offset of the current matching element relative to its positioned ancestor element, that is, the coordinates relative to the positioned ancestor element. This function only works on visible elements.

The so-called "positioned element" means that the CSS position attribute value of the element is absolute, relative or fixed (as long as it is not the default static).

This function returns a coordinate object, which has a left attribute and a top attribute. Property values ​​are all numbers, and they are all in pixels (px).

The difference from offset() is that position() returns the coordinates relative to the positioned ancestor element, and offset() returns the coordinates relative to the current document. Additionally, the position() function cannot be used for setting operations. If all the ancestor elements of the current element are default positioned (static), then the offset position returned by this function is the same as the offset() function.

This function belongs to the jQuery object (instance).

Grammar

This function is new in jQuery 1.2.

1

jQueryObject.position( )

Copy after login

Return value

The return value of the position() function is of type Object, returning an offset coordinate object relative to the nearest "positioned" ancestor element. This object has left and top attributes.

If the current jQuery object matches multiple elements, when returning coordinates, the position() function only uses the first matching element. If there are no matching elements, undefined is returned.

The coordinate reference system in position() is based on the upper left corner of the positioned ancestor element as the origin (0,0), positive to the right and positive downward.

Examples & Instructions

Take the following HTML code as an example:

1

2

3

<br>

<br>

<p id="n1"><span id="n2">专注于编程开发技术分享</span></p>

Copy after login

The following jQuery sample code is used to demonstrate the usage of position() function and offset() function:

1

2

3

4

5

6

var $n2 = $("#n2");

// 输出n2的偏移坐标

var pos = $n2.position();

document.writeln( "n2的position()偏移坐标:(" + pos.left + ", " + pos.top + ")" ); // n2的position()偏移坐标:(8, 60)

var coord = $n2.offset();

document.writeln( "n2的offset()的偏移坐标:(" + coord.left + ", " + coord.top + ")" ); // n2的offset()的偏移坐标:(8, 60)

Copy after login

From the above jQuery operation results, we can see that position() does not obtain the offset position relative to its parent element. If all the ancestor elements of n2 are default positioned, the offset position returned by position() is consistent with the offset() function.

Next, we add relative positioning to n1 in the above HTML code:

1

2

3

<br>

<br>

<p id="n1" style="position: relative;" ><span id="n2">专注于编程开发技术分享</span></p>

Copy after login

Then, we re-execute the above jQuery code and you can see the following results:

1

2

3

4

5

6

var $n2 = $("#n2");

// 输出n2的偏移坐标

var pos = $n2.position();

document.writeln( "n2的position()偏移坐标:(" + pos.left + ", " + pos.top + ")" ); // n2的position()偏移坐标:(0, 0)

var coord = $n2.offset();

document.writeln( "n2的offset()的偏移坐标:(" + coord.left + ", " + coord.top + ")" ); // n2的offset()的偏移坐标:(8, 60)

Copy after login

At this time, among the ancestor elements of n2, n1 is the nearest positioned ancestor element to n2 (here it is relative, the same is true for absolute and fixed), so position() returns the offset position of n2 relative to n1.

. Application of position function in jQuery (centering, off-screen processing, etc.)

jQuery provides a Position function, which can easily position Html elements. The simple usage method is as follows:

1

2

3

4

5

6

7

8

9

$(".daygrid").click(function(event){

  clickedGrid = $(this);

  $(".modal").modal("show");

  $(".modal").position({

    of:clickedGrid,

    offset:" ",

    collision:"fit"

  });

});

Copy after login

The above is a very common usage, register a click time, and then when a click event occurs, obtain the clicked element, and then display the dialog box to the interface using the position method.

The position function accepts an options object with many parameters

of: Indicates the object to be placed on, you can also pass the event object of click

my and at: These two are not easy to understand. In fact, they are the reference object and the referenced object. The my parameter indicates the position used for reference and at indicates the position of the reference target. The value range is any one or two of "left center right top bottom". For example: my:"top left",at:"left buttom", this configuration means that the upper left corner of the element to be set is placed in the lower left corner of the target element.

collision: Indicates how to handle collisions. The value range is: "flip fit none". Choose one of three. The official English description of flip is not very clear. The actual test effect is that if it exceeds the expected range (such as window), it will try to place the element in the opposite position of the target area. Fit is adaptation, which means that the element will be placed completely within the expected range without letting the element overflow. And none does not do any collision processing.

offset indicates how much distance to offset after aligning the elements with my, at, and of. For example, setting it to "100 100" means moving to the target position and then offset 100px downward and right

A common use is the position of the pop-up dialog box. In order to make the dialog box display at the position where the mouse clicks, you can pass the event object passed by click to the of parameter, and in order to ensure that the dialog box is within the scope of the window, you can use collision Set to fit. Finally, set the alignment parameters my and at according to actual needs, and use offset to fine-tune the offset. An example of setting the pop-up dialog box in the center of the window:

1

2

3

4

5

6

$("#myDialog").position({

  my: "center",

  at: "center",

  of: window,

  collision:"fit"

});

Copy after login

The above content is the detailed explanation of the jQuery position() function and the entire description of the application of the position function in jQuery that the editor has shared with you. I hope you like it.

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How do I use source maps to debug minified JavaScript code? How do I use source maps to debug minified JavaScript code? Mar 18, 2025 pm 03:17 PM

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

TypeScript for Beginners, Part 2: Basic Data Types TypeScript for Beginners, Part 2: Basic Data Types Mar 19, 2025 am 09:10 AM

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

See all articles