我使用下面的jquery让我的链接滚动到下一个div。然而,我遇到了一个问题。从页面的顶部看,脚本运行良好。只要我单击另一个div中的链接(页面下面的另一个链接),脚本就只能向上或向下滚动,而不会滚动到下一个指定的div。如何使脚本从链接所在位置的当前位置完全滚动?
$(function() {
$('#nav a').bind('click',function(event){
var $anchor = $(this);
$('html, body, #container, .main').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top
}, 1500,'easeInOutExpo');
event.preventDefault();
});
});发布于 2013-04-03 02:12:14
你打错地方了..。
这应该能起作用..。首先设置锚点。
$(function() {
$('#nav a').bind('click',function(event){
var $anchor = $(this).attr('href');
$('html, body, #container, .main').stop().animate({
scrollTop: $($anchor).offset().top
}, 1500,'easeInOutExpo');
event.preventDefault();
});
});发布于 2013-04-03 02:14:54
这里有一个错误:
scrollTop: $($anchor.attr('href')).offset().top
//------^^^^^^^---------------------------------this itself a selector更改为此并尝试:
scrollTop: $anchor.attr('href').offset().top或者这个也是:
$('#nav a').bind('click',function(event){
var $anchor = $(this).attr('href');
$('html, body, #container, .main').stop().animate({
scrollTop: $($anchor).offset().top
}, 1500,'easeInOutExpo');
event.preventDefault();
});发布于 2013-04-03 18:07:16
好的,我已经为您创建了一个JSFiddle,我将js代码重写为下面的代码,但是您可以在这里查看完整的代码:http://jsfiddle.net/re7Xc/
$(function() {
$('a.scrolltonext').click(function(event){
event.preventDefault();
var parentblock = $(this).parent();
var nextblock = parentblock.next();
//nextblock.css('background-color','#00f');
if(nextblock.size()>0) {
$('html, body').stop().animate({
'scrollTop': nextblock.offset().top
}, 800);
}
});
});这个脚本的问题是我把链接放在div本身中,这样它就不会在#nav中。所以如果你把链接放到你的#nav中,你必须重写这一部分!
我也在里面放了一个if语句,因为我觉得在滚动之前先检查是否有下一个div会更好。
希望它有一些意义,并让我知道它是否对你有效!干杯
https://stackoverflow.com/questions/15771195
复制相似问题