我的页面上有几个超链接。一个常见问题,用户将阅读时,他们访问我的帮助部分。
使用锚链接,我可以使页面滚动到锚,并引导用户到那里。
有没有办法使滚动流畅?
但请注意,他使用的是自定义JavaScript库。也许jQuery提供了这样的功能?
我的页面上有几个超链接。一个常见问题,用户将阅读时,他们访问我的帮助部分。
使用锚链接,我可以使页面滚动到锚,并引导用户到那里。
有没有办法使滚动流畅?
但请注意,他使用的是自定义JavaScript库。也许jQuery提供了这样的功能?
当前回答
此解决方案也适用于以下url,而不会破坏指向不同页面的锚点链接。
http://www.example.com/dir/index.html
http://www.example.com/dir/index.html#anchor
./index.html
./index.html#anchor
etc.
var $root = $('html, body');
$('a').on('click', function(event){
var hash = this.hash;
// Is the anchor on the same page?
if (hash && this.href.slice(0, -hash.length-1) == location.href.slice(0, -location.hash.length-1)) {
$root.animate({
scrollTop: $(hash).offset().top
}, 'normal', function() {
location.hash = hash;
});
return false;
}
});
我还没有在所有浏览器中测试这个功能。
其他回答
我对"/xxxxx#asdf"和"#asdf" href锚都这样做了
$("a[href*=#]").on('click', function(event){
var href = $(this).attr("href");
if ( /(#.*)/.test(href) ){
var hash = href.match(/(#.*)/)[0];
var path = href.match(/([^#]*)/)[0];
if (window.location.pathname == path || path.length == 0){
event.preventDefault();
$('html,body').animate({scrollTop:$(this.hash).offset().top}, 1000);
window.location.hash = hash;
}
}
});
经过测试和验证的代码
<script>
jQuery(document).ready(function(){
// Add smooth scrolling to all links
jQuery("a").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
jQuery('html, body').animate({
scrollTop: jQuery(hash).offset().top
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
</script>
使用JQuery:
$('a[href*=#]').click(function(){
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
return false;
});
我建议你编写这样的泛型代码:
$('a[href^="#"]').click(function(){
var the_id = $(this).attr("href");
$('html, body').animate({
scrollTop:$(the_id).offset().top
}, 'slow');
return false;});
您可以在这里看到一篇非常好的文章:jquery- effect -smooth-scroll- pollution -fluide
不要忘记offset()函数将元素的位置传递给文档。所以当你需要滚动你的元素相对于它的父元素时你应该使用这个;
$('.a-parent-div').find('a').click(function(event){
event.preventDefault();
$('.scroll-div').animate({
scrollTop: $( $.attr(this, 'href') ).position().top + $('.scroll-div').scrollTop()
}, 500);
});
关键点是获得scroll-div的scrollTop,并将其添加到scrollTop。如果你不这样做,position()函数总是会给你不同的位置值。