简体   繁体   中英

Function on resize doesn't work

Hello I have problem with really easy script. It should change class if under 768 px of window width but it just doesn't work. I have no clue why. I dont want to use media queries in this in this case.

Here's code:

<!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>

I started your script. For 768px and more there is class 'aside', for 767px and less class 'sidebar'. So where is the problem?

If you open page on width less than 768 your script won't be working correct. You have to add it to event onload too

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