是的,我知道“on”方法,这里关于“on”的大部分答案都不具体。有人可以帮我这个代码吗?
$(function(){
var pagePositon = 0,
sectionsSeclector = 'article#sector',
$scrollItems = $(sectionsSeclector),
offsetTolorence = 30,
pageMaxPosition = $scrollItems.length - 1;
//Map the sections:
$scrollItems.each(function(index,ele) { $(ele).attr("debog",index).data("pos",index); });
// Bind to scroll
$(window).bind('scroll',upPos);
//Move on click:
$(document).keypress(function(e) {
if (e.which == 100 && pagePositon+1 <= pageMaxPosition) {
pagePositon++;
$('html, body').stop().animate({
scrollTop: $scrollItems.eq(pagePositon).offset().top
}, 300);
}
if (e.which == 97 && pagePositon-1 >= 0) {
pagePositon--;
$('html, body').stop().animate({
scrollTop: $scrollItems.eq(pagePositon).offset().top
}, 300);
return false;
}
});
//Update position func:
function upPos(){
var fromTop = $(this).scrollTop();
var $cur = null;
$scrollItems.each(function(index,ele){
if ($(ele).offset().top < fromTop + offsetTolorence) $cur = $(ele);
});
if ($cur != null && pagePositon != $cur.data('pos')) {
pagePositon = $cur.data('pos');
}
}
});
当你按“d”或“a”时,它会转到下一个或上一个id =“sector”,这很好。但偶尔,在Ajax Call之后和追加新文章后,脚本无法移动到它们。我知道他们没有绑定(在dom刷新之后)以及如何在Ajax dom更改后使该脚本工作?
答案 0 :(得分:0)
解决了:
$(function(){
var pagePositon = 0,
sectionsSeclector = 'article#sector',
$scrollItems = $(sectionsSeclector),
offsetTolorence = 30,
pageMaxPosition = $scrollItems.length - 1;
//Map the sections:
// Bind to scroll
//Move on click:
$(document).on('keypress', function(e) {
$scrollItems = $(sectionsSeclector);
pageMaxPosition = $scrollItems.length - 1;
$scrollItems.each(function(index,ele) { $(ele).attr("debog",index).data("pos",index); });
$(window).bind('scroll',upPos);
if (e.which == 100 && pagePositon+1 <= pageMaxPosition) {
pagePositon++;
$('html, body').stop().animate({
scrollTop: $scrollItems.eq(pagePositon).offset().top
}, 300);
}
if (e.which == 97 && pagePositon-1 >= 0) {
pagePositon--;
$('html, body').stop().animate({
scrollTop: $scrollItems.eq(pagePositon).offset().top
}, 300);
return false;
}
});
//Update position func:
function upPos(){
var fromTop = $(this).scrollTop();
var $cur = null;
$scrollItems.each(function(index,ele){
if ($(ele).offset().top < fromTop + offsetTolorence) $cur = $(ele);
});
if ($cur != null && pagePositon != $cur.data('pos')) {
pagePositon = $cur.data('pos');
}
}
});