Home > Article > Web Front-end > How to achieve page scrolling with jquery without changing element position
Two methods: 1. Use css() to add a fixed positioning style to the matching element, the syntax is "$(selector).css("position", "fixed")". 2. Use attr() to set the style attribute and add a fixed positioning style to the matching element. The syntax is "$(selector).attr("style", "position: fixed;");".
The operating environment of this tutorial: windows7 system, jquery3.6.1 version, Dell G3 computer.
The page scrolls while the position of the element remains unchanged. This can be achieved by adding fixed positioning to the element.
Fixed positioning (position:fixed
):
The element is positioned relative to the browser window, no matter how it is moved Your slider will be fixed at a fixed position relative to the browser window. Also note that its sibling elements will ignore its presence in positioning. The top, bottom, left, and right used at this time are also relative to the browser window.
Two ways to add fixed positioning to elements using jquery
1. Use css()
# The ##css() method returns or sets one or more style properties of the matching element. Syntax for setting css styles$(selector).css(name,value)
Description | |
---|---|
name | Required. Specifies the name of the CSS property. This parameter can contain any CSS property, such as "color".|
value | Optional. Specifies the value of a CSS property. This parameter can contain any CSS property value, such as "red". If the empty string value is set, removes the specified attribute from the element. |
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-3.6.0.min.js"></script> <script> $(function() { $("button").click(function() { $(".pos_abs").css("position", "fixed"); }) }) </script> <style type="text/css"> h2.pos_abs { /* position: fixed; */ left: 100px; /* 设置定位元素的左偏移值 */ top: 80px; /* 设置定位元素的上偏移值 */ } p { height: 50px; background-color: palegoldenrod; } p.p2 { margin-top: 100px; } </style> </head> <body style="height: 1200px;"> <h2 class="pos_abs">这是需要固定定位的标题</h2> <p>相对于浏览器窗口来对元素进行定位</p> <p class="p2">相对于浏览器窗口来对元素进行定位</p> <button>固定h2元素,让其位置不变</button> </body> </html>
attr() method sets the attributes and values of the selected element.
$(selector).attr(attribute,value)
When you use the attr() method to set the style attribute of an element, you can add a fixed positioning style to the element.
$(function() { $("button").click(function() { $(".pos_abs").attr("style", "position: fixed;"); }) })
[Recommended learning:
, web front-end introductory video]
The above is the detailed content of How to achieve page scrolling with jquery without changing element position. For more information, please follow other related articles on the PHP Chinese website!