2016-05-29 46 views
0

我想寫的jQuery代碼,這將使頁面滾動到div而不是立即去那裏,並儘可能簡單。我已經爲李元素添加了所需div的id。平滑滾動li元素的onclick

我的HTML代碼如下所示:

<li id="#slide1" class="active" onclick="javascript:location.href='#slide1'"><a href="#slide1" title="Next Section" >About</a></li> 
    <li id="#slide2" onclick="javascript:location.href='#slide3'"><a href="#slide2" title="Next Section">Works</a></li> 
    <li id="#slide3" onclick="javascript:location.href='#slide3'"><a href="#slide3" title="Next Section">Contact</a></li> 
    <li id="#slide4" onclick="javascript:location.href='#slide4'"><a href="#slide4" title="Next Section">belekas</a></li> 
    <li id="#slide5" onclick="javascript:location.href='#slide5'"><a href="#slide3" title="Next Section">dar vienas</a></li> 

,我想這jQuery代碼,但它不工作。所以也許任何人都可以幫助我?

$('li').click(function(){ 
    var target = $(this).attr('id'); 
    $("html, body").animate({ 
    scrollTop: target.offset().top 
     }, 1000); 
    return false; 
}); 

UPDATE:https://jsfiddle.net/j452hL2w/這裏是我的導航

+0

小提琴請 – Patrick2607

+0

@ Patrick2607用小提琴更新了問題。 –

回答

2

的小提琴版我從每一個列表項刪除每一個onclick="javascript:location.href='#slide'"。這不是必須的,因爲你在javascript中創建了clickhandlers。

我這個替換您的點擊功能:

$('li').click(function(e) { 
    // Prevent default action (e.g. jumping to top of page) 
    e.preventDefault(); 
    // Create a variable with the link found in the list-item 
    var link = $(this).children('a');  
    // Animate the document 
    $('html,body').animate({ 
    // Gets the href from the link ('slideX') and scrolls to it on the page. 
    scrollTop: $(link.attr('href')).offset().top 
    // 'slow'(600ms) can be replaced by 'fast'(200ms) or a number in ms. 
    // The default is 400ms 
    }, 'slow'); 
}); 

這裏是updated fiddle