Home > Web Front-end > JS Tutorial > Code that uses onresize to make divs adapt to the size of the screen_javascript skills

Code that uses onresize to make divs adapt to the size of the screen_javascript skills

WBOY
Release: 2016-05-16 18:36:20
Original
1505 people have browsed it

When we center a div, there are generally two methods. One is to fix the left and right width, that is, use pixel absolute positioning; the other is to use percentages for relative positioning. In these two methods, absolute positioning cannot be The div adapts to the screen, and you can use percentages. However, there will be a new problem if you use percentages. If there is such a sentence in our page

When When I said this sentence, everything was normal, but I don’t know why this standard statement caused such inconvenience
In response to this problem, I used the following method to realize the adaption of div
First of all, I used The method is absolute positioning. First set the left, right, top and bottom margins of the div. Add two events in body,

getwah() is used to get the size of the screen and div each margin, and calculate their difference

Copy the code The code is as follows:

var height,width,width_cha1,width_cha2;
function getwah()
{
if(document.documentElement && document.documentElement.clientWidth)
{d_width = document.documentElement.clientWidth;}
else if(document.body)
{d_width = document.body.clientWidth;}
width=parseInt(d_width);
width_cha1=width-parseInt(document.getElementById("backi").style. left)
width_cha2=width-parseInt(document.getElementById("massage_box").style.left)
}

Trigger test() when the screen size changes (onresize) function, this function is for the user to reset the margins of the div based on the difference between the screen and the margins obtained previously, so that when the size of the screen changes, the margins of the div will also change accordingly, so that the div can be adjusted accordingly. Adapt to changes in screen size
Copy code The code is as follows:

function test()
{
if(document.documentElement && document.documentElement.clientWidth)
{d_width = document.documentElement.clientWidth;}
else if(document.body)
{d_width = document.body .clientWidth;}
var now_left1=parseInt(d_width )-width_cha1;
var now_left2=parseInt(d_width )-width_cha2;
document.getElementById("backi").style.left=now_left1
document.getElementById("massage_box").style.left=now_left2
}
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