垂直滚动的媒体查询 [英] media query for vertical scroll
问题描述
有没有一种方法可以通过媒体查询来检测垂直滚动距离?
Is there a way to detect vertical scroll distance with a media query?
似乎媒体查询是围绕检测媒体而设计的(向右震撼:P)诸如浏览器高度之类的东西是可以测试的,但是不能具体地滚动页面向下滚动的距离。
It seems that media queries are designed around detecting the medium (shocking right :P) so things like browser height are testable, but not specifically how far down the page is scrolled.
如果不可能,但是您知道使用JS(不是jQuery)的感觉免费发布!
If is not possible, but you know a way in JS (not jQuery) feel free to post!
推荐答案
我认为CSS媒体查询不可行,但我确实知道滚动高度可以在JavaScript中使用 window.pageYOffset
找到。如果您希望每次用户在页面上上下滚动时都通过一个函数运行此值,则可以执行以下操作
I don't believe it's possible with a CSS media query, but I do know that the scroll height can be found in JavaScript using window.pageYOffset
. If you wanted to run this value through a function every time the users scrolled up or down on a page, you could do something like
window.onscroll = function() {
scrollFunctionHere(window.pageYOffset);
};
或者只是:
window.onscroll = scrollFunctionHere;
如果函数本身检查了 window.pageYOffset $ c的值$ c>。
有关如何在JavaScript中有效使用 window.onscroll
的更多建议,请参考< a href = https://stackoverflow.com/a/23690891/1846065> mynameistechno的答案。
For more advice on how to do use window.onscroll
efficiently in JavaScript, refer to mynameistechno's answer.
关于效率的重要提示:如果在回调中执行任何不重要的操作,则每次发出滚动事件时都运行一次函数可能会破坏CPU周期。取而代之的是,好的做法是仅允许一个回调每秒运行多次。
Important note on efficiency: running a function every single time a scroll event is emitted can tear through CPU cycles if anything non-trivial is performed in the callback. Instead, it is good practice to only allow a callback to run so many times per second. This has been termed "debouncing".
下面的简单去抖动滚动事件处理程序代码。请注意,文本如何每250ms(而不是每帧)在 HELLO和 WORLD之间切换:
Simple debounced scroll event handler code below. Notice how the text toggles between "HELLO" and "WORLD" every 250ms, rather than every single frame:
var outputTo = document.querySelector(".output");
var timeout_debounce;
window.addEventListener("scroll", debounce);
function debounce(event) {
if(timeout_debounce) {
return;
}
timeout_debounce = setTimeout(clearDebounce, 250);
// Pass the event to the actual callback.
actualCallback(event);
}
function clearDebounce() {
timeout_debounce = null;
}
function actualCallback(event) {
// Perform your logic here with no CPU hogging.
outputTo.innerText = outputTo.innerText === "HELLO"
? "WORLD"
: "HELLO";
}
p {
padding: 40vh;
margin: 20vh;
background: blue;
color: white;
}
<p class="output">Test!</p>
这篇关于垂直滚动的媒体查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!