2016-09-09 15 views
0

只是想知道如何启用使用完整的url平滑滚动。jQuery的光滑滚动完整的网址,包括编号

这是导航

<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代码。

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); 
    } 
    }); 
} 

任何帮助将非常感谢。

+0

你是问,如果你可以点击从所在的页面#不存在,并且走到哪里它确实存在的页面#,然后滚动至#? – Tom

+0

如果域名在那里,它将重新加载页面/转到新页面。如果您想要进入新页面然后滚动,您需要查找页面加载事件并在URL中查找“#”。 –

+0

类似于: - [https://stackoverflow.com/questions/7717527/smooth-scrolling-when-clicking-an-anchor-link](https://stackoverflow.com/questions/7717527/smooth-scrolling-当点击一个锚点链接) –

回答

0

据我了解,你想留在同一页面上,只是出于某种原因,你希望你的内部链接是绝对的。

为了实现与绝对URL的内部链接,你可以改变它这样的:

的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”,但网址激活您更改选择'http://domainname.com/#about'。然后你切断域名部分,你会有一个像'#about'的内部链接。

小提琴:https://jsfiddle.net/u5dL9rt3/

+0

谢谢迈克尔,正是我所期待的。 – Ollie

+0

我很高兴我能帮上忙。你能否把答案标记为接受? –

+0

请在这里查看如何注册/接受答案:https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work –