当用户在可以使用的特定文本框中滚动时,是否存在js侦听器?除了滚动之外,Kinda喜欢onclick。我看到用于数字输入滚动的HTML5事件侦听器-仅Chrome,但这似乎仅适用于chrome。我正在寻找跨浏览器的东西。
对于那些发现此问题以希望找到不涉及jQuery的答案的人,您可以window
使用常规事件侦听来陷入“滚动”事件。假设我们要添加滚动,以监听许多CSS-selector-able元素:
// what should we do when scrolling occurs
var runOnScroll = function(evt) {
// not the most exciting thing, but a thing nonetheless
console.log(evt.target);
};
// grab elements as array, rather than as NodeList
var elements = document.querySelectorAll("...");
elements = Array.prototype.slice.call(elements);
// and then make each element do something on scroll
elements.forEach(function(element) {
window.addEventListener("scroll", runOnScroll, {passive: true});
});
(使用被动属性告诉浏览器此事件不会干扰滚动本身)
为了获得加分,可以为滚动处理程序提供一种锁定机制,以便在我们已经滚动的情况下它不会运行:
// global lock, so put this code in a closure of some sort so you're not polluting.
var locked = false;
var lastCall = false;
var runOnScroll = function(evt) {
if(locked) return;
if (lastCall) clearTimeout(lastCall);
lastCall = setTimeout(() => {
runOnScroll(evt);
// you do this because you want to handle the last
// scroll event, even if it occurred while another
// event was being processed.
}, 200);
// ...your code goes here...
locked = false;
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句