Using JS to find screen height, then apply it to a div class through CSS

主宰稳场 提交于 2019-12-05 14:30:02

What you are asking for is not difficult at all. All it requires is one nice JavaScript function and a few quick minor changes to your HTML code.

First, give your "container" <div> an id by making some quick changes to your HTML;

<div class="container" id="container">
I want this container to be the height of the users screen resolution. 
</div>

Next define a JavaScript variable that refers to it:

var container = document.getElementById("container");

Then use this neat function that I use all the time to get the dimensions of the screen using JavaScript:

function resize() {
    // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight

if (typeof window.innerWidth != 'undefined') {
    viewportwidth = window.innerWidth,
    viewportheight = window.innerHeight
}

// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)

else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) {
    viewportwidth = document.documentElement.clientWidth,
    viewportheight = document.documentElement.clientHeight
}

// older versions of IE

else {
    viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
    viewportheight = document.getElementsByTagName('body')[0].clientHeight
}
container.style.height = viewportheight+"px";
}

Notice that I put container.style.height = viewportheight+"px"; in the function. This means that every time resize(); is called we will update the dimensions of the browser and reapply those dimensions to the container <div>.

We will call the resize(); function in the body every time the page resizes, as well as when the page first loads, using this HTML:

<body onload="resize()" onresize="resize()">

The function will resize the container <div> to the full page height. Let me know if you have problems with this, or have any questions!

You Can not use JS code in css.

You may do what you want like this:

$('.container').height($(window).height());

or

$('.container').height($(document).height());

whether you want window or document height.

You CAN NOT do following stuff

.container { width:100%; height: /* javascript value */ }

However you can set height to some value and later alter it using jQuery's .css() API.

Also make sure that you call your matchHeight() function from within $(documeent).ready().

===========================

You can change your container class to

.container { position:absolute: width:100%; height: 100%; }

===========================

OR you can use css media queries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!