First of all, let’s explain in detail the meaning of several size attributes of windows and web pages in JS
document.body.clientWidth (visible area width of web page): refers to the width of the area where the browser displays the web page, excluding the browser’s The width of the border and the width of the vertical scroll bar. The size changes with the browser window size.
document.body.clientHeight (visible area height of web page): refers to the height that can be seen in the area where the browser displays the web page, excluding the browser's border width and the height of the horizontal scroll bar. The size changes with the browser window size.
document.body.scrollTop (the height of the webpage being scrolled): refers to the height of the part of the webpage that is covered by the address bar and menu bar when the vertical scroll bar is pulled.
document.body.scrollLeft (the left side of the webpage being scrolled): refers to the width of the left side of the webpage that is covered by the left line when the horizontal scroll bar is pulled.
Now let’s analyze how to implement the program:
The first step we want to achieve is to make the layer absolutely centered when it pops up, regardless of whether there is a scroll bar.
1. Calculate the position of the layer distance from the left and top of the display area
Note: divId refers to the layer to be centered, and divId.clientWidth is its width! @
var divId = document.getElementById("xxx");
var v_left=(document.body.clientWidth-divId.clientWidth)/2;
var v_top=(document.body.clientHeight-divId .clientHeight)/2;
2. Reassign the obtained values to the left and top attributes of the DIV
divId.style.left=v_left;
divId.style.top=v_top;
Explanation : divId is the id value of the DIV tag
In this way, this layer will be displayed in the center.
The second step we want to achieve is to center the layer that pops up when the scroll bar is dragged.
In fact, it is very simple. We only need to add the dragged width and height to the left margin and top margin calculated previously.
v_left =document.body.scrollLeft;
v_top =document.body.scrollTop;
2. Reassign the obtained values to the left and top attributes of the DIV
divId.style.left=v_left ;
divId.style.top=v_top;
It will be displayed in the center.
The complete code is as follows: