简体   繁体   中英

How can I dynamically get browser height and width?

What im looking to do is create a chatbox that doesn't rely on media queries. That mathematically sets sizes of the chatbox content.

I was experimenting with $(window).height()/$(window).width() but that doesn't cover the whole browser window. I wanted to do this all in javascript/jquery without css/media queries

Try this code snippet

 (function() { window.onresize = displayWindowSize; window.onload = displayWindowSize; function displayWindowSize() { let myWidth = window.innerWidth; let myHeight = window.innerHeight; // your size calculation code here document.getElementById("screen").innerHTML = myWidth + "x" + myHeight; }; })();
 <div id="screen"></div>

window.innerWidth and window.innerHeight will give this answer in native JavaScript without any library.

If you want to get the dimensions of a specific HTML Element, you could instead use offsetWidth and offsetHeight , eg document.body.offsetWidth

Not exactly sure what you're doing without seeing your code, but when you divide height by width as you do above, you only get a ratio, which is probably why you're not seeing the results you expect?

如果$(window).height()没有返回整个浏览器窗口大小,那么你有结构问题,比如<!DOCTYPE html>可能不是你的 HTML 文件的第一行等。

I ran into a similar problem relating to a nav bar that needed a click event handler on mobile and a hover event handler on desktop. Eventually I found the JS media query function matchMedia() which worked well with setTimeout() so it doesn't run on every pixel change.

My solution can be found here: https://stackoverflow.com/a/60837961/7353382

If you want to set the maxWidth or minWidth browser screen size like media query dynamically in JavaScript and then define styles or anything else, you can use the Window interface's matchMedia() method. It will return a new MediaQueryList object that can then be used to determine if the document matches the media query string, as well as to monitor the document to detect when it matches (or stops matching) that media query.

Ok, the syntax:

const pageWidth = window.matchMedia('(min-width: 600px)');

and we can use the object that returns in different ways:

     const handlePageColor = () => {
    if (pageWidth.matches) {
        document.body.style.backgroundColor = "yellow";
    }
};

And finally you should addListener() method to our object, this causes our function to run whenever the browser screen size changes.

    pageWidth.addListener(handlePageColor);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM