Home >Web Front-end >Front-end Q&A >How to achieve top positioning in javascript

How to achieve top positioning in javascript

藏色散人
藏色散人Original
2021-10-25 14:30:584890browse

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)
        }

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!

Statement:
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