我想导航到一个新页面上的锚点,但我希望页面加载在顶部,然后立即平滑滚动到相关的锚点。这能办到吗?
我是个有Javascript的新手。
这是我目前用来在当前页面中平滑滚动的js。我只是在链接上应用了一个“滚动”类。
非常感谢!
<script>
$(function(){
$('.scroll').on('click',function(e) {
e.preventDefault();
$('html, body').animate({ scrollTop: $($(this).attr('href')).offset().top + 'px' }, 1000, 'swing');
});
});
</script>发布于 2022-08-25 13:16:29
这里有一种更现代的方法,看起来效果很好。这必须放在任何document.ready或window.onLoad处理程序之外。
// Handle page load
if ( window.location.hash ) {
var target = window.location.hash.slice( 1 );
if ( document.getElementById( target ) ) {
$( function() {
if ( window.location.hash ) {
if ( $( '#' + target ).length ) {
window.scrollTo( 0, 0 );
$( 'html, body' ).animate( {
scrollTop: $( '#' + target ).offset().top - 50
}, 800 );
}
}
} );
if ( 'scrollRestoration' in history ) {
history.scrollRestoration = 'manual';
}
window.scrollTo( 0, 0 );
}
}
// Handle anchor links
$( function() {
$( 'a[href^="#"]' ).on( 'click', function( e ) {
e.preventDefault();
$( 'html, body' ).animate( {
scrollTop: $( $.attr( this, 'href' ) ).offset().top - 80
}, 800 );
return false;
} );
} );https://stackoverflow.com/questions/30293784
复制相似问题