调整大小的功能不起作用

Function on resize doesn't work

您好,我对非常简单的脚本有疑问。如果 window 宽度小于 768 像素,它应该更改 class 但它不起作用。我不知道为什么。在这种情况下,我不想在这种情况下使用媒体查询。

代码如下:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>ez</title>
    <style>
    .aside {
        float: left; 
        height: 1000px; 
        width: 250px; 
        background-color: grey;
        }
    .sidebar {
        position: absolute;
        top: 0;
        left: -250px;
        }
    </style>
</head>
<body style="height: 2000px">

<aside class="aside" id="aside"></aside>
<main style="float: left; height: 1000px; width: 70%; background-color: black;"></main>        

<script>
var elm = document.getElementById("aside");    

function change() {
    var w = window.innerWidth;
    if(w<768) {
        elm.className = "sidebar";
    } else {
        elm.className = "aside";
    }
}


window.addEventListener("resize", change);
</script>
</body>
</html>

我开始了你的脚本。对于 768px 和更多有 class 'aside',对于 767px 和更少 class 'sidebar'。那么问题出在哪里呢?

如果您打开宽度小于 768 的页面,您的脚本将无法正常工作。你也必须将它添加到事件 onload