简体   繁体   中英

How to trigger media Queries in javascript for style.width

I'm working on a onclick event (html) with jquery. In my jquery i set the width for this event.

Though i want a different width for the mobile website. For this I should work with media queries. On desktop it is 50vw, on phone (triggered from 600px) it should be 100vw... Though how to make this work properly?

function openMenu() {
document.getElementById("menuNav").style.width = "50vw"; 
}

function closeMenu() {
    document.getElementById("menuNav").style.width = "0vh";
}

Define .open class and .closed class in CSS where you can use media queries normally. Then switch CSS classes on menuNav with JavaScript. See documentation for classList: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

if($(window).width() < 601) { 
    // change functionality for smaller screens
} else { 
    // change functionality for larger screens
}e

or

if(window.matchMedia('(max-width: 600px)').matches)
{
    // do functionality on screens smaller than 600px
}

You can use jQuery's width() method to find the width of the window (IE the browser viewport) and determine whether 50vw or 100vw should be used:

function openMenu() {
    if($(window).width() > 600) {
        document.getElementById("menuNav").style.width = "50vw";
    } else {
        document.getElementById("menuNav").style.width = "100vw"; 
    }
}

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