此代碼最初用於在頁面加載時平滑滾動到錨點。相同功能的jquery,onclick和onload事件
試圖添加一個監聽器,以便它可以在點擊滾動到錨點在同一頁上,但我卡住了。
// <!--smooth scroll to anchors-->
(function(jQuery){
var jump=function(e){
if (e){
e.preventDefault(); //prevent the "normal" behavior which would be a "hard" jump
var mytarget = jQuery(this).attr("href"); //get the target
}else{
var mytarget = location.hash; //sets the target to the anchor part of a URL
}
jQuery('html,body').animate( //perform animated scrolling
{
scrollTop: jQuery(mytarget).offset().top - 100 //get top-position of target-element and set it as scroll target and move down 100px for fixed nav
}, 1000,function(){ //scrolldelay: 2 seconds
location.hash = mytarget; //attach the hash (#jumptarget) to the pageurl
});
}
jQuery('html, body').hide()
// on load
jQuery(document).ready(function(){
jQuery('a[href^="#"]').bind("click", jump);
if (location.hash){
setTimeout(function(){
jQuery('html, body').scrollTop(0).show()
jump()
}, 0);
}else{
jQuery('html, body').show()
}
});
// on click
var inpage-nav =document.querySelectorAll('.in-page-nav');
for(var i=0;i<cell.length;i++){
inpage-nav[i].addEventListener('click',jump);
}
})(jQuery)
// <!--End smooth scroll-->
HTML在頁面導航:
<div class="just-a-nav">
<ul>
<li class="filter"><a class="in-page-nav" href="#item1">Item 1</a></li>
<li class="filter"><a class="in-page-nav" href="#item2">Item 2</a></li>
<li class="filter"><a class="in-page-nav" href="#item3">Item 3</a></li>
</ul>
</div>
_Trying添加listener_ - 這裏是你的聽衆? –
什麼是您的HTML?你可以顯示具有「in-page-nav」類的HTML部分嗎? –
@RezaMamun已添加到原始問題。 – justsomeone