Home  >  Article  >  Web Front-end  >  How to put the window on top in javascript

How to put the window on top in javascript

藏色散人
藏色散人Original
2021-10-14 15:00:453587browse

How to implement window top in JavaScript: 1. Create a front-end sample file; 2. Get the distance from the element to the top of the browser window through getBoundingClientRect; 3. Use a loop to keep the element on top.

How to put the window on top in javascript

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

How to put the window on top in JavaScript?

JavaScript implements the pinned function

There are many ways to implement the pinned function with JavaScript. I have used some before. I think it is more complicated. I need it for something I have recently done, so I also use it online. After searching for some information, I 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 loops is to make the elements at the top unobtrusive. This process can be achieved by changing i. At the same time, it should be noted that if the for statement uses var i instead of 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 study: "javascript basic tutorial"

The above is the detailed content of How to put the window on top 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