簡體   English   中英

我可以讓這個媒體查詢在我的 javascript 中工作嗎?

[英]Can I make this media query work in my javascript?

我試圖讓我的網站知道它何時高於 1096 以執行一些 CSS 樣式,這是我的代碼

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");
} 

請有人告訴我為什么這不起作用? 先感謝您

編輯:我不能使用 CSS,它必須在 javascript 中

如果你想讓你的媒體在屏幕尺寸超過 1096 時響應,你應該改用min-width: 1096px max-width: 1096px當屏幕小於或等於目標尺寸時捕獲。

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 */
}

要么:

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 */
}

另外window.parent.document.getElementsByClassName()沒有意義,改成document.getElementsByClassName()

你不需要javascript來做到這一點。

您可以僅使用 css 媒體查詢來完成相同的行為,如下所示:

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

但是,如果你想使用 javascript,你可以像這樣獲得窗口寬度:

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

您可以創建一個事件偵聽器並使用窗口對象來獲取視口尺寸。

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

匹配媒體文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM