简体   繁体   中英

How to apply this Javascript code on desktop only?

I want to modify this code to make it work only on dekstop devices.

For my case, dekstop is anything above 640px.

Here is the original code:

var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
  var currentScrollPos = window.pageYOffset;
  if (prevScrollpos > currentScrollPos) {
    document.getElementById("shopify-section-header").style.top = "0";
  } else {
    document.getElementById("shopify-section-header").style.top = "-150px";
  }
  prevScrollpos = currentScrollPos;
}

 var prevScrollpos = window.pageYOffset; if (window.innerWidth > 640) { window.onscroll = function() { var currentScrollPos = window.pageYOffset; if (prevScrollpos > currentScrollPos) { document.getElementById("shopify-section-header").style.top = "0"; } else { document.getElementById("shopify-section-header").style.top = "-150px"; } prevScrollpos = currentScrollPos; } }

From the MDN Docs ( https://developer.mozilla.org/en-US/docs/Web/API/window/innerWidth ):

The read-only Window property innerWidth returns the interior width of the window in pixels. This includes the width of the vertical scroll bar, if one is present.

More precisely, innerWidth returns the width of the window's layout viewport. The interior height of the window—the height of the layout viewport—can be obtained from the innerHeight property.

Alternatives:

  • If you can use jQuery: $(window).width()
  • document.documentElement.clientWidth matches the @media queries in css but only when there is no scrollbar
  • window.innerWidth exactly matches css @media queries.

For more about the differences, see How to get the browser viewport dimensions?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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