How to achieve top positioning in javascript

藏色散人
Release: 2021-10-25 14:30:58
Original
4886 people have browsed it

Javascript method to implement the top function: 1. Get the distance from the element to the top of the browser window through getBoundingClientRect; 2. Implement the top function through the "$(document).scrollTop() for(...)" method. Can.

How to achieve top positioning in javascript

The operating environment of this article: windows7 system, javascript version 1.8.5, Dell G3 computer.

JavaScript implements the pinned function

There are many ways to implement the pinned function with JavaScript. I have used some before. It feels more complicated. I need it for something I have recently done, so I also searched for some information on the Internet, and finally found a method getBoundingClientRect() that can get the distance from the page element to the top of the browser window.

The final code is as follows:

let len = document.getElementById('flexbox').getBoundingClientRect().top;//获取元素到浏览器视窗顶部的距离
//$(document).scrollTop()为滚动条的高度
        for (let i = $(document).scrollTop(); i < len + $(document).scrollTop(); i++) {
            setTimeout(function () {
                window.scrollTo(0, i);
            }, 0)
        }
Copy after login

The main purpose of using a loop is to make the element not obtrusive when it is placed on top. This process can be achieved by changing i. At the same time, one thing needs to be noted. If the for statement is used It is var i rather than let i. The timer needs to be wrapped with an immediate execution function to ensure that i can take effect immediately.

The effects of sticking to top and anchor points achieved in this way are similar. If you want to achieve floating top (a certain part is fixed on the top), you can consider using position:fixed to achieve it.

So be it. . . .

[Recommended learning: javascript basic tutorial]

The above is the detailed content of How to achieve top positioning in javascript. For more information, please follow other related articles on the PHP Chinese website!

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