Home > Article > Web Front-end > How to get and set the element position in jquery
Jquery is a very popular JavaScript library. One of the very important functions is to manipulate elements on the page. In web development, we often need to get and set the position of elements, which is a very important function. This article will introduce how to use Jquery to get and set the position of elements.
1. Get the element position
offset() method returns the position of the element relative to the upper left corner of the page. The code is as follows:
$(document).ready(function(){ var offset = $("#box").offset(); console.log(offset.left); console.log(offset.top); });
position() method returns the position of the element relative to the upper left corner of its parent element. The code is as follows:
$(document).ready(function(){ var position = $("#box").position(); console.log(position.left); console.log(position.top); });
scrollTop() method returns the vertical distance of the current page scrolling. The code is as follows:
$(document).ready(function(){ var scrollTop = $(window).scrollTop(); console.log(scrollTop); });
2. Set the element position
offset() method can set the position of the element relative to the upper left corner of the page Location. The code is as follows:
$(document).ready(function(){ $("#box").offset({left:100, top:200}); });
css() method can set the CSS properties of the element. For example, you can set the left and top properties of an element to change its position. The code is as follows:
$(document).ready(function(){ $("#box").css({left:100, top:200}); });
The animate() method can smoothly change the position of an element over a period of time. The code is as follows:
$(document).ready(function(){ $("#box").animate({left:100, top:200}, 1000); });
This article introduces how to use Jquery to get and set the position of elements. These methods are very useful and can help us implement complex page layouts. Hope this article is helpful to you.
The above is the detailed content of How to get and set the element position in jquery. For more information, please follow other related articles on the PHP Chinese website!