Home > Web Front-end > JS Tutorial > Detailed explanation of jQuery's position() method_jquery

Detailed explanation of jQuery's position() method_jquery

WBOY
Release: 2016-05-16 15:49:39
Original
1543 people have browsed it

Definition and usage of position() method:

This method gets the offset of the matched element relative to some element.

The returned object contains an object with two integer attributes (top and left).

This method only works on visible elements.

Grammar structure:

$(selector).position()
Copy after login

At the beginning of the tutorial, the reason why it is said is to get the offset of the matching element relative to some elements. Many tutorials say that the offset returned by the method is relative to the parent element, but this is not entirely true. This method will process the matching element with absolute positioning. Of course, it does not mean that the matching element is actually set to absolute positioning. The offset reference principle of the method is as follows:

1. If the parent element does not use positioning (the position attribute value is relative, absolute or fixed), then the offset reference object is the window.

2. If any of the parent elements uses positioning, then the reference object of the offset is the nearest element that uses positioning,

Example code:

<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<style type="text/css">
*{
 margin:0px;
 padding:0px;
}
.father{
 background-color:green;
 width:200px;
 height:200px;
 padding:50px;
 margin-bottom:50px;
 margin-left:100px;
}
.children{
 height:150px;
 width:150px;
 background-color:red;
 line-height:150px;
 text-align:center;
}
</style>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
 $(".children").each(function(){
  var text;
  text="left:"+$(this).position().left;
  text+="top:"+$(this).position().top;
  $(this).text(text);
 })
})
</script>
</head>
<body>
<div class="father" style="position:relative">
 <div class="children"></div>
</div>
<div class="father">
 <div class="children"></div>
</div>
</body>
</html>

Copy after login

In the top combination in the above code, since the parent element uses relative positioning, the obtained offset is relative to the parent element. In the bottom combination, since the parent element does not use positioning, the offset reference object is the window.

The above is the entire content of this article, I hope you all like it.

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template