简体   繁体   中英

How to run a function automatically in JavaScript based on screen size

I'm doing responsive web design. When I shrink the screen down to tablet mode and click some buttons, certain CSS properties are applied(things are moved around and others are hidden). Then when I enlarge the screen back to its desktop size. I want the properties to go back to the desktop version. How would I achieve that?

The current behavior is that the effect of the button remains when I go back to the desktop screen ratio. The expected behavior is that when I go back to the desktop screen ratio, the CSS for desktop applies.

You can access certain properties such as window.innerWidth which you can check to decide whether to run your function or not.

That's for JavaScript. If you want your CSS to be responsive to screen size, check media queries , for example:

@media (min-height: 680px) {
    .someClass {
        margin: 5px;
    }
}

You can use CSS media queries.

@media screen and (max-width: 600px) and (min-width: 300px) {
  /* CSS for screen width between 300 and 600px */
}

With JavaScript, you could listen for the resize event.

window.addEventListener("resize", function(e){
    console.log(window.innerWidth);
});

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