0

我需要在以下代码中添加 matchMedia 查询,以便它仅在 1366px 的视口宽度处激活,我尝试了一些不同的选项,但没有任何效果。

<script type="text/javascript">

// When the user scrolls down 80px from the top of the document, resize the navbar's padding and the logo's font size

$(document).ready(function(){

window.addEventListener('scroll', scrollFunction);
window.addEventListener('scroll', progressBarFunction);

var winScroll = document.body.scrollTop || document.documentElement.scrollTop;
var height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
var scrolled = (winScroll / height) * 100;

function scrollFunction() {

  if (document.body.scrollTop > 80 || document.documentElement.scrollTop > 80) {

    document.getElementById("logoImg").style.width = "123px";
    document.getElementById("logoImg").style.margin = "18px 40px";
    document.getElementById("button-container-super").style.top = "-5px";
    document.getElementById("menu-text").style.padding = "0.6em 0.9em 0em 0.9em";
    document.getElementById("digital").style.opacity = "0";
    document.getElementById("myBar").style.width = scrolled + "%";

  } else {

    document.getElementById("logoImg").style.width = "170px";
    document.getElementById("logoImg").style.margin = "30px 40px";
    document.getElementById("button-container-super").style.top = "8px";
    document.getElementById("menu-text").style.padding = "1.5em 0.9em 0em 0.9em";
    document.getElementById("digital").style.opacity = "1";
  }
}
});
</script>

我将不胜感激任何帮助。

谢谢马克

4

1 回答 1

0

https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia

matchMedia返回具有属性的对象matches

一个布尔值,如果文档当前与媒体查询列表匹配,则返回 true,否则返回 false。

function scrollFunction() {
  const mq = window.matchMedia("(min-width: 1366px)");

  if (mq.maches) {
    if (
      document.body.scrollTop > 80 ||
      document.documentElement.scrollTop > 80
    ) {
      document.getElementById("logoImg").style.width = "123px";
      document.getElementById("logoImg").style.margin = "18px 40px";
      document.getElementById("button-container-super").style.top = "-5px";
      document.getElementById("menu-text").style.padding =
        "0.6em 0.9em 0em 0.9em";
      document.getElementById("digital").style.opacity = "0";
      document.getElementById("myBar").style.width = scrolled + "%";
    } else {
      document.getElementById("logoImg").style.width = "170px";
      document.getElementById("logoImg").style.margin = "30px 40px";
      document.getElementById("button-container-super").style.top = "8px";
      document.getElementById("menu-text").style.padding =
        "1.5em 0.9em 0em 0.9em";
      document.getElementById("digital").style.opacity = "1";
    }
  }
}
于 2020-05-10T19:06:34.197 回答