简体   繁体   中英

Can I make this media query work in my javascript?

i'm trying to get my site to know when it's above 1096 to execute some CSS styling, here is my code

var mq = window.matchMedia('@media all and (max-width: 1096px)');
if(mq.matches) {
    window.parent.document.getElementsByClassName("sticky-leaderboard-ad-container")[0].setAttribute("style","padding-top: 4rem !important; margin-left: 0 !important");
} 

please can someone let me know why this isn't working? thank you in advance

edit: i can't use CSS, it must be in javascript

If you want to make your media respond when the screen size above 1096, you should instead use min-width: 1096px . max-width: 1096px captures when the screen is lower or equal to the target size.

if (window.matchMedia("(max-width: 1096px)").matches) {
  /* The viewport is less than, or equal to, 1096px pixels wide */
} else {
  /* The viewport is greater than 1096px pixels wide */
}

or:

if (window.matchMedia("(min-width: 1096px)").matches) {
  /* The viewport is greater than, or equal to, 1096px pixels wide */
} else {
  /* The viewport is less than 1096px pixels wide */
}

Besides window.parent.document.getElementsByClassName() doesn't make sense, change it to document.getElementsByClassName()

You don't need javascript to do that.

You can use only css media queries to accomplish the same behavior like this:

@media all and (max-width: 1096px)
.sticky-leaderboard-ad-container {
     padding-top: 4rem !important; 
     margin-left: 0 !important;
}

But, if you want to use javascript you can get the window width like this:

if(window.innerWidth < 1096) {
        let element = document.getElementsByClassName("sticky-leaderboard-ad-container")[0];
        element.setAttribute("style","padding-top: 4rem !important; margin-left: 0 !important");
} 

You could create an event listener and make use of the window object to get the viewport dimensions.

window.innerWidth 
window.innerHeight
window.matchMedia("(min-width: 1096px)")

matchMedia docs

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