链接跳转到底部和顶部,但不会平滑滚动,即使我确定 JS 正在工作。
JS:
$.fn.ready(function() {
// Smooth scroll to top.
$("a[href=#top]").live("click", function(e) {
$("html,body").animate({scrollTop:0}, 1000);
e.preventDefault();
});
// Smooth scroll to bottom.
$("a[href=#bot]").live("click", function(e) {
$("html,body").animate({scrollTop:$(document).height()}, 1000);
e.preventDefault();
});
});
HTML:
<a href="#bot" id="botlink" title="Go to bottom">↓</a>
<a href="#top" id="toplink" title="Go to top">↑</a>
最佳答案
如果您使用“实时”事件,我猜您使用的是旧版本的 jQuery。 因为你想继续在顶部/底部,你知道它们在某些位置(顶部 = 0,底部 = document.height)。一个有效的 jquery 代码将是这样的:
jQuery(document).ready(function($){
$('#botlink').add( $('#toplink') ).on( 'click', function( e ){
e.preventDefault();
var $btn = $(this).attr( 'id' ).replace('#', '');
var move_to = $btn === 'botlink' ? $(document).height() : 0;
$('body').animate({
scrollTop : move_to
}, 'slow');
});
});
当用户点击 #botlink
或 toplink
时,上面的代码会进行检查。在 move_to
变量中,它会检查单击了哪个按钮(阅读“short if”)并计算页面应该在何时移动。 要产生有效效果,您需要为 html
和 body
设置动画。
实际上它只对 body
有效。你还有一个 js fiddle here (我强制 body 在 1200px 上生长以便能够看到效果)
关于javascript - 链接跳转到顶部和底部但平滑滚动不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26060139/