Home  >  Article  >  Daily Programming  >  How to determine screen size in JS

How to determine screen size in JS

藏色散人
藏色散人Original
2018-12-18 16:30:3318004browse


Use JS to determine the current screen size. We can use the Window matchMedia() method to match the specified size element, and then judge it with the current screen size.

How to determine screen size in JS

Now we will introduce the JS method to determine the current screen size with a simple code example.

The code example is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>JS判断屏幕大小示例</title>

</head>
<body>
<script>
 if(window.matchMedia("(max-width: 767px)").matches){
        document.write("这是一个移动设备。");
 }else {
        document.write("这是平板电脑或台式电脑。");
 }
</script>
</body>
</html>

Here we write a screen size judgment to match the given maximum width size (767px) through the matchMedia method. When the obtained current screen, that is, the window size, is less than 767 pixels, it is determined that "this is a mobile device." On the contrary, when it is larger than 767 pixels, it is judged as "this is a tablet or desktop computer."

The judgment results are as follows:

When the current screen width is greater than 767px:

How to determine screen size in JS

When the current screen width is less than 767px:

How to determine screen size in JS

matchMedia() Returns a new MediaQueryList object, representing the parsed result of the specified media query string. The value of the matchMedia() method can be any characteristic of the CSS @media rule, such as min-height, min-width, orientation, etc.

The MediaQueryList object has the following two properties:

media: The content of the query statement.

matches: Used to detect query results. If the document matches the media query list, the value is true, otherwise it is false.

This article is an introduction to the JS method of judging screen size. It is simple and easy to understand. I hope it will be helpful to friends in need!


The above is the detailed content of How to determine screen size in JS. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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