I have a single page website with multiple anchors. I am referencing this fiddle example for advancing the page to the next anchor when the mouse scrollwheel is used. Is there any way for me to modify this to also account for spacebar scrolling?
(function() {
var delay = false;
$(document).on('mousewheel DOMMouseScroll', function(event) {
event.preventDefault();
if(delay) return;
delay = true;
setTimeout(function(){delay = false},200)
var wd = event.originalEvent.wheelDelta || -event.originalEvent.detail;
var a= document.getElementsByTagName('a');
if(wd < 0) {
for(var i = 0 ; i < a.length ; i++) {
var t = a[i].getClientRects()[0].top;
if(t >= 40) break;
}
}
else {
for(var i = a.length-1 ; i >= 0 ; i--) {
var t = a[i].getClientRects()[0].top;
if(t < -20) break;
}
}
$('html,body').animate({
scrollTop: a[i].offsetTop
});
});
})();
http://jsfiddle.net/kamikazefish/t6LLybx8/201/
(function() {
var delay = false;
$(document).on('mousewheel DOMMouseScroll', function(event) {
event.preventDefault();
if(delay) return;
delay = true;
setTimeout(function(){delay = false},200)
var wd = event.originalEvent.wheelDelta || -event.originalEvent.detail;
var links = document.getElementsByTagName('a');
var link;
if(wd < 0) {
link = findNext(links);
}
else {
link = findPrevious(links);
}
animate(link);
});
$('body').keydown(function(e){
if(e.keyCode == 8){
e.preventDefault();
// user has pressed backspace
var links = document.getElementsByTagName('a');
link = findPrevious(links);
animate(link);
}
if(e.keyCode == 32){
e.preventDefault();
// user has pressed space
var links = document.getElementsByTagName('a');
link = findNext(links);
animate(link);
}
});
function findNext(links) {
for(var i = 0 ; i < links.length ; i++) {
var t = links[i].getClientRects()[0].top;
if(t >= 40) return links[i];
}
}
function findPrevious(links) {
for(var i = links.length-1 ; i >= 0 ; i--) {
var t = links[i].getClientRects()[0].top;
if(t < -20) return links[i];
}
}
function animate(link) {
if( link ) {
$('html,body').animate({
scrollTop: link.offsetTop
});
}
}
})();
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.