首页 > 解决方案 > 当屏幕尺寸大于 700 像素时,如何使用 javascript 只让我的标题菜单缩小?

问题描述

下面是我的网站: KaiNanfelt_Music

我试图让我的标题(菜单)在滚动时缩小,整个代码看起来像这样:

所以它适用于所有屏幕,但我希望它仅在屏幕尺寸大于 700px 时才有效,我应该如何处理它和任何建议?谢谢!

// When the user scrolls down 80px from the top of the document, resize the navbar's padding and the logo's font size
window.onscroll = function() {
  scrollFunction()
};

function scrollFunction() {
  if (document.body.scrollTop > 80 || document.documentElement.scrollTop > 80) {
    document.getElementById("menu").style.padding = "0px";
    document.getElementById("menu").style.margin = "0px 0px 0px 10px";
    document.getElementById("site-title").style.fontSize = "3.5em";
    document.getElementById("site-title").style.float = "left";
    document.getElementById("site-title").style.margin = "20px 0 10px 0";
    document.getElementsByClassName("menu").style.float = "right";
  } else {
    document.getElementById("menu").style.padding = "10px";
    document.getElementById("site-title").style.fontSize = "6.8em";
    document.getElementById("site-title").style.float = "none";
  }
}
#menu {
  transition: 0.5s;
  position: fixed;
  width: 100%;
  top: 0;
  z-index: 200;
  overflow: hidden;
  background: #ffffff;
  ;
}
<nav id="menu">
  <button class="nav-button">Toggle Navigation</button>
  <div id="site-title">
    <a href="#" title="home" rel="home">
      Home
    </a>
  </div>
</nav>

标签: javascripthtmljquerycss

解决方案


在条件语句中使用带有 clientWidth 的 documentElement 来查看屏幕宽度是否大于 700,如果是,请运行您的函数...

注意:我在示例中使用了 600 像素,因为片段中的视口低于 700

var viewportWidth = window.innerWidth || document.documentElement.clientWidth;
console.log('current viewport: ' + viewportWidth)
window.onscroll = function() {
  if (viewportWidth > 600) {
    //<-- console.log just to illustrate that the sizing works, resize your screen and test
    console.log(' Window is larger than 600 px');
    // run your scrollFunction()
  }
};
<!--Force a scroll using break tags for testing--><br>
'view in full screen'<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>


推荐阅读