如何仅在桌面应用此 Javascript 代码?
How to apply this Javascript code on desktop only?
我想修改此代码以使其仅适用于桌面设备。
就我而言,桌面大于 640px。
原代码如下:
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;
}
}
来自 MDN 文档 (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.
备选方案:
- 如果可以使用jQuery:
$(window).width()
document.documentElement.clientWidth
匹配 css 中的 @media
查询,但仅当没有滚动条时
window.innerWidth
完全匹配 css @media
查询。
有关差异的更多信息,请参阅 How to get the browser viewport dimensions?
我想修改此代码以使其仅适用于桌面设备。
就我而言,桌面大于 640px。
原代码如下:
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;
}
}
来自 MDN 文档 (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.
备选方案:
- 如果可以使用jQuery:
$(window).width()
document.documentElement.clientWidth
匹配 css 中的@media
查询,但仅当没有滚动条时window.innerWidth
完全匹配 css@media
查询。
有关差异的更多信息,请参阅 How to get the browser viewport dimensions?