[英]Script for detecting the screen size,and change css according to screen size
I got this script for detecting the size of the window -我得到了这个用于检测窗口大小的脚本 -
function myFunction() { var w = window.innerWidth; var h = window.innerHeight; if (w = 768) { document.getElementById("container").style.height = "15.155em"; } else if (w = 1024) { document.getElementById("container").style.height = "25.155em"; } else if (w = 1366) { document.getElementById("container").style.height = "35.155em"; } }
<body onload="myFunction()"> <div id="container" style="width:50px;border:2px solid black;"> </div> </body>
What i would like to happen,is each time the height of the div would change,according to the size of window.我想要发生的是,每次 div 的高度都会根据窗口的大小而改变。
Whats happening now,is on every screen i run the website its showing me as if the screen size is the "768"现在发生了什么,在我运行网站的每个屏幕上都显示我好像屏幕大小是“768”
You don't need javascript for this: it can be done entirely with css.你不需要为此使用 javascript:它可以完全用 css 来完成。 You have a few options (that I can think of right now):你有几个选择(我现在能想到的):
Hope that helps!希望有帮助!
html, body { margin: 0; padding: 0; height: 100% } div { width: 100px; height: 100%; background: red; }
<div></div>
You can use CSS instead of using JS.您可以使用 CSS 而不是使用 JS。 Use the following CSS to fit the DIV to whatever size of the screen is.使用以下 CSS 使 DIV 适合屏幕的任何尺寸。
#container
{
position: absolute;
overflow-x: hidden;
overflow-y:auto;
width: 100%;
height: 100%;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
Also you can use height:100vh
but this Unit will not be support in older browser.您也可以使用height:100vh
但旧浏览器不支持此单元。
Thanks谢谢
because actual browser width is always lesser than screen resolution , and u are using screen resolution for comparison.因为实际的浏览器宽度总是小于屏幕分辨率,并且您正在使用屏幕分辨率进行比较。
if (w = 768)
else if (w = 1024)
else if (w = 1366)
Either use要么使用
if(w<768)
//do something
else if(w<1024)
//do something
else if(w<1366)
//do something
else
//default
Or better use或者更好的使用
screen.width
screen.height
if you want to use = as comparator.如果你想使用 = 作为比较器。
It is because in a if condition to evaluate there should be == and not =.这是因为在要评估的 if 条件中应该是 == 而不是 =。 What you have used is an assignment operator and not comparision.您使用的是赋值运算符而不是比较。
Please correct the code as below请更正以下代码
function myFunction()
{
var w = window.innerWidth;
var h = window.innerHeight;
if (w == 768) {
document.getElementById("container").style.height = "15.155em";
} else if (w == 1024) {
document.getElementById("container").style.height = "25.155em";
} else if (w == 1366) {
document.getElementById("container").style.height = "35.155em";
}
}
As other members suggested mediaQueries is a good option in case you are looking to make it responsive.正如其他成员所建议的那样,如果您希望使其具有响应性,则 mediaQueries 是一个不错的选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.