jQuery平滑滚动包括ID的完整URL [英] jQuery smooth scroll full url including id
问题描述
只是想知道如何使用完整的URL进行平滑滚动.
Just wondering how to enable smooth scroll using full url.
这是导航
<nav class="primary-nav">
<ul>
<li><a href="http://domainname.com/">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#services">Services</a></li>
<li><a href="http://domainname.com/contact">Contact</a></li>
</ul>
</nav>
要使用
<nav class="primary-nav">
<ul>
<li><a href="http://domainname.com/">Home</a></li>
<li><a href="http://domainname.com/#about">About</a></li>
<li><a href="http://domainname.com/#services">Services</a></li>
<li><a href="http://domainname.com/contact">Contact</a></li>
</ul>
</nav>
这是用于滚动到页面各部分的jQuery代码.
and this is the jQuery code used to scroll to sections on the page.
function smoothScroll(duration) {
$('a[href^="#"]').on('click', function (event) {
var target = $($(this).attr('href'));
if (target.length) {
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top
}, duration);
}
});
}
任何帮助都将非常感谢.
Any help would be great thanks.
推荐答案
据我了解,由于某些原因,您希望内部链接是绝对的,因此您希望保留在同一页面上.
As far as I understand you want to stay on the same page, just for some reason you want your internal links to be absolute.
要实现使用绝对URL的内部链接,您可以像这样更改它:
To achieve internal linking with absolute URLs you could change it like that:
JavaScript:
JavaScript:
var duration = 1000;
var domainname = 'http://domainname.com/';
$('a[href^="'+domainname+'#"]').on('click', function (event) {
var target = $(this).attr('href');
if (target.length) {
event.preventDefault();
target = $( target.replace(domainname, '') );
$('html, body').animate({
scrollTop: target.offset().top
}, duration);
}
});
说明:您更改选择器,以使其不会在"#about"之类的URL上激活,而在" http://domainname之类的URL上激活.com/#about ".然后,切断域名部分,您将再次获得一个内部链接,例如"#about".
Explanation: You change the selector so that it not activates on URLs like '#about' but 'http://domainname.com/#about'. Then you cut off the domain name part and you will have a internal link like '#about' again.
提琴: https://jsfiddle.net/u5dL9rt3/
这篇关于jQuery平滑滚动包括ID的完整URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!