I'm designing a very simple web page(HTML only), the only "feature" I want to implement is to do something when the user scrolls down the page, is there a way to capture that "event" somehow?
问题:
回答1:
Just for completeness, there's another solution using another JS framework (Mootools)
window.addEvent('scroll',function(e) {
//do stuff
});
回答2:
If you don't want to use jQuery (which you might not do for a very simple HTML page), you can accomplish this using regular Javascript:
<script>
function scrollFunction() {
// do your stuff here;
}
window.onscroll = scrollFunction;
</script>
You mentioned that you wanted to do something when they scroll down the page - the onscroll event fires off scrolling in any direction, in either the x- or y-axis, so your function will be called any time they scroll.
If you really want it to only run your code when they scrolled down the page, you'd need to preserve the previous scroll position to compare against whenever onscroll gets called.
回答3:
You can't do it with just HTML, you'll need to use Javascript. I recommend using jQuery, so your solution can look like this:
$(document).ready(function() {
$(window).scroll(function() {
// do whatever you need here.
});
});
If you don't want or are unable to use jQuery, you can use the onscroll
solution posted by Anthony.
回答4:
A better way is to not only check for scroll events but also for direction scrolling like below;
$(window).bind('mousewheel', function(event) {
if (event.originalEvent.wheelDelta >= 0) {
console.log('Scroll up');
}
else {
console.log('Scroll down');
}
});
回答5:
u can simply use this
window.addEvent('scroll',function(e) {
if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
// enter code here
}
});
回答6:
This works for me.
var previousPosition
$(window).scroll(function(){
var currentScrollPosition=$(window).scrollTop() + $(window).height()
if (currentScrollPosition>previousScrollPosition) {
console.log('down')
}else if(currentScrollPosition<previousScrollPosition){
console.log('up')
}
previousScrollPosition=currentScrollPosition
});