Home >Web Front-end >Front-end Q&A >How to set the position of an element in jquery
Setting method: 1. Use offset() to set the offset coordinate of the element relative to the document, the syntax is "element object.offset({top: offset value, left: offset value})"; 2. Use scrollTop() to set the vertical scroll bar position of the element; 3. Use scrollLeft() to set the horizontal scroll bar position of the element.
The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.
Many ways to set the position of elements in jquery
1. Use offset()
The offset() method sets the offset coordinates of the selected element relative to the document.
$(selector).offset({top:value,left:value})
Specifies the top and left coordinates in pixels.
Example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <script src="js/jquery-1.10.2.min.js"></script> <style> p { width:150px; background-color:pink; padding: 5px; } </style> <script> $(document).ready(function() { $("button").click(function() { $("p").offset({ top: 200, left: 200 }); }); }); </script> </head> <body> <p>这是一个段落。</p> <button>设置P元素的偏移坐标</button> </body> </html>
2. Use scrollTop()
scrollTop( ) method sets the vertical scroll bar position of the selected element.
$(selector).scrollTop(position)
Tip: When the scroll bar is at the top, the position is 0.
Example:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-1.10.2.min.js"></script> <script> $(document).ready(function() { $("button").click(function() { $("div").scrollTop(100); }); }); </script> </head> <body> <div style="border:1px solid black;width:100px;height:150px;overflow:auto"> This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. </div><br> <button>垂直滚动条的位置设置为100px</button> </body> </html>
3. Use scrollLeft()
scrollLeft() Yes Sets the offset of the matching element relative to the left side of the scroll bar, that is, the position of the horizontal scroll bar.
$(selector).scrollLeft(position)
The horizontal position of the scroll bar refers to the number of pixels scrolled from its left side. When the scroll bar is at the far left, the position is 0.
Example:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-1.10.2.min.js"></script> <script> $(document).ready(function() { $("button").click(function() { $("div").scrollLeft(100); }); }); </script> </head> <body> <div style="border:1px solid black;width:100px;height:130px;overflow:auto"> The longest word in the english dictionary is: pneumonoultramicroscopicsilicovolcanoconiosis. </div><br> <button>水平滚动条的位置设置为100 px</button> </body> </html>
[Recommended learning: jQuery video tutorial, web front-end video]
The above is the detailed content of How to set the position of an element in jquery. For more information, please follow other related articles on the PHP Chinese website!