如何设置JavaScript的“if”条件以根据移动屏幕大小触发?

huangapple go评论119阅读模式
英文:

How can I set a javascript "if" conditional to activate based on mobile screen size?

问题

我有一个JavaScript代码可以在滚动时使标题缩小目前我正在使用以下代码

...

我想要修改代码以便在移动设备上初始时标题就是缩小的这样在窗口宽度小于768px时就永远不会出现全尺寸的标题

我尝试过添加以下代码但并没有起作用

...

任何帮助或指导将不胜感激

提前致谢
英文:

I have a javascript code which causes the header to scale on scroll. Currently, I am using this:

<script>
  var y = window.scrollY
  var hh = document.getElementById('header').offsetHeight
  var shrinkHeader = function(){
    console.log("y", window.scrollY)
    if(window.scrollY === 0){
      document.getElementById('header').style.height = '125px';
      document.getElementById('content').style.paddingTop = '125px';
      document.getElementById('header').classList.remove("small-image");
    }else{
      if(hh === 80){return;}else{
        document.getElementById('header').style.height = '70px';
        document.getElementById('content').style.paddingTop = '70px';
        document.getElementById('header').classList.add("small-image");
      }
    }
  }
  window.onload = shrinkHeader;
  window.onscroll = shrinkHeader;
</script>

I would like to modify so that the header initiates as shrunk on mobile. So that there is never a full size header when viewing on a window less than 768px.

I've tried adding this, however it did not work:

<script>
  var y = window.scrollY
  var hh = document.getElementById('header').offsetHeight
  var shrinkHeader = function(){
    console.log("y", window.scrollY)
    if(window.scrollY === 0 && $(window).width() > 768){
      document.getElementById('header').style.height = '125px';
      document.getElementById('content').style.paddingTop = '125px';
      document.getElementById('header').classList.remove("small-image");
    }else{
      if(hh === 80 || $(window).width() < 769){return;}else{
        document.getElementById('header').style.height = '70px';
        document.getElementById('content').style.paddingTop = '70px';
        document.getElementById('header').classList.add("small-image");
      }
    }
  }
  window.onload = shrinkHeader;
  window.onscroll = shrinkHeader;
</script>

Any help or redirection is appreciated.

Many thanks in advance.

答案1

得分: 1

使用Window:matchMedia()方法
示例:

if (window.matchMedia('(max-width: 768px)').matches) {
  console.log('max-width: 767px');
} else {
  console.log('min-width: 768px');
}
英文:

Use Window: matchMedia() method
Example:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

if ( window.matchMedia(&#39;(max-width: 768px)&#39;).matches ) {
  console.log(&#39;max-width: 767px&#39;);
} else {
  console.log(&#39;min-width: 768px&#39;);
}

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年7月7日 00:45:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76630968.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定