简体   繁体   English

JavaScript 中的 Window.matchMedia 不起作用

[英]Window.matchMedia in JavaScript not functioning

I have an HTML, CSS and JavaScript files.我有一个 HTML、CSS 和 JavaScript 文件。 The HTML contains three quotes which shuffles every two seconds. HTML 包含三个引号,每两秒洗牌一次。 I have written the JavaScript code to show these quotes only when the screen width is at most 600px.我编写了 JavaScript 代码,仅当屏幕宽度最多为 600 像素时才显示这些引号。 The problem is that the quote continues to display across every screen width.问题是报价继续显示在每个屏幕宽度上。 I've tried using the media query in CSS, but to no avail.我尝试在 CSS 中使用媒体查询,但无济于事。 What might be the issue?可能是什么问题? Please, see code below.请看下面的代码。

HTML Code: HTML 代码:

<div class="preNavBar">
        <div class="quoteWrapper">
            <span class="quote">The roots of education are bitter, but the fruit is sweet. &nbsp;</span>
            <span class="quoteAuthor">&#8212; Aristotle</span>
        </div>
        <div class="quoteWrapper">
            <span class="quote">To teach is to learn twice. &nbsp;</span>
            <span class="quoteAuthor">&#8212; Unknown</span>
        </div>
        <div class="quoteWrapper">
            <span class="quote">A person who won't read has no advantage over one who can't read. &nbsp;</span>
            <span class="quoteAuthor">&#8212; Mark Twain</span>
        </div>
    </div>

CSS Code: CSS 代码:

body {
    padding: 0 !important;
    margin: 0 !important;
    font-size: 16pxm;
    background: rgb(53, 54, 58);
}

* {
    box-sizing: border-box;
    /* margin: 0; */
    padding: 0;
}

/* PRE-NAVIGATION BAR */
.preNavBar {
    background-color: navy;
    color: white;
    padding: 10px 30px;
    display: grid;
    justify-content: center;
}

.preNavBar .quoteAuthor {
    font-weight: bolder;
    float: right;
}

@media only screen and (min-width: 768px) {
    /* .preNavBar .quoteWrapper{
        display: none;
    } */
}

JavaScript Code: JavaScript 代码:

<script>
        let x = window.matchMedia("(max-width: 600px)");
        if (x.matches) {
            showQuote();
            function showQuote() {
                let slides = document.getElementsByClassName("quoteWrapper");
                let i;
                for (i = 0; i < slides.length; i++) {
                    slides[i].style.display = "none";
                }

                let min = 0;
                let max = slides.length - 1;
                let randNum = Math.floor(Math.random() * (max - min + 1)) + min;

                slides[randNum].style.display = "block";

                setTimeout(showQuote, 2000); // change every 2 seconds
            }
        }
    </script>

Let's take a look at the very first line:让我们看一下第一行:

let x = window.matchMedia("(max-width: 800px)");

You invoke window.matchMedia and store returned value in x .您调用window.matchMedia并将返回值存储在x中。

The important thing here is that x will not change if screen is resized after the moment it was declared.这里重要的是,如果屏幕在声明后调整大小, x不会改变。

If you want it to, you'll need a resize event listener .如果你愿意,你需要一个resize 事件监听器。

Also, a possible pitfall here is that depending on where in the document your <script> tag is placed, you might want to wrap all your code into an IIFE to ensure it fires after the document is completely loaded.此外,这里可能存在的一个缺陷是,根据您的<script>标签在文档中的位置,您可能希望将所有代码包装到IIFE中,以确保它在文档完全加载后触发。

That's because you set the variable on start and never change it on resize那是因为您在开始时设置了变量,并且在调整大小时从不更改它

let timeout;
function testMatch() {
    let x = window.matchMedia("(max-width: 800px)");
    if (x.matches) {
        function showQuote() {
            let slides = document.getElementsByClassName("quoteWrapper");

            for (let i = 0; i < slides.length; i++) {
                slides[i].style.display = "none";
            }

            //the min was 0 so it was useless, if you do slides.length-1, 
            //you wont be able to access the last index
            let randNum = Math.floor(Math.random() * slides.length);
            slides[randNum].style.display = "block";
            //set it so you can clear if user changes to > 600px
            timeout = setTimeout(showQuote, 2000); // change every 2 seconds
        }

        showQuote();
    } else if (timeout) {
        clearTimeout(timeout);
    }
}

testMatch();
addEventListener("resize", testMatch);

Also this could be a lot more efficiently done by using an id to signify which quote is not hidden.此外,通过使用 id 来表示哪个引用未被隐藏,这可以更有效地完成。

(function () {
  const slides = document.getElementsByClassName("quoteWrapper");
  let timeout;

  function testMatch() {
    let x = window.matchMedia("(max-width: 800px)");
    if (x.matches) {
      function showQuote() {
        //the min was 0 so it was useless, if you do slides.length-1, 
        //you wont be able to access the last index
        let randNum = Math.floor(Math.random() * slides.length);

        const prev = document.getElementById("current-quote");
        if (prev) prev.removeAttribute("id");
        slides[randNum].setAttribute("id", "current-quote");
        timeout = setTimeout(showQuote, 2000); // change every 2 seconds
      }

      showQuote();
    } else if (timeout) {
      clearTimeout(timeout);
    }
  }

  testMatch();
  addEventListener("resize", testMatch);
})();
.quoteWrapper {
  display: none;
}

#current-quote {
  display: block;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM