Home > Daily Programming > HTML Knowledge > How to get the position of the current element in jquery

How to get the position of the current element in jquery

藏色散人
Release: 2018-12-27 11:02:53
Original
9078 people have browsed it


jquery gets the position of the current element, and it is relative to the position of the document. We can use the jQuery offset() method to achieve this. The offset() method only works on visible elements.

How to get the position of the current element in jquery

Below we combine simple code to introduce to you how jquery gets the position of the current element.

The code example is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jquery获取当前元素的位置</title>
<style type="text/css">
*{
margin:0;
padding:0;
}
    #box{
        width:150px;
        height:100px;
        background: orange;
        margin: 150px 100px;
    }
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
    $(function() {
        $("button").click(function(){
            var offset = $("#box").offset();
            alert("盒子的当前位置为: (left: " + offset.left + ", top: " + offset.top + ")");
        });
    });
</script>
</head>
<body>
    <button type="button">获取位置</button>
  
</body>
</html>
Copy after login

offset() method returns or sets the offset (position) of the matching element relative to the document.

The .offset() method allows us to retrieve the current position of an element relative to the document (specifically its bounding box, which excludes margins). Contrast this with .position(), which retrieves the current position relative to the offset parent. .offset() is more useful when doing global operations (especially implementing drag and drop) when placing a new element on top of an existing element.

.offset() returns an object containing attributes top and left.

Get the position of the current element, the result is as follows:

How to get the position of the current element in jquery

This article is about jquery method of getting the position of the current element, it is also very simple, I hope Help those in need!


The above is the detailed content of How to get the position of the current element in jquery. For more information, please follow other related articles on the PHP Chinese website!

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