简体   繁体   English

平滑滚动li元素的onclick

[英]Smooth scrolling onclick of li element

I'm trying to write jQuery code which would make the page scroll to the div instead of going there immediately and to make it as simple as possible. 我正在尝试编写jQuery代码,以使页面滚动到div而不是立即转到该div,并使其尽可能简单。 I have added ids of desired divs to li elements. 我已将所需div的ID添加到li元素中。

My html code looks like this: 我的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>

and I tried this jQuery code but it doesn't work. 而且我尝试了这个jQuery代码,但是没有用。 So maybe anyone could help me? 那么也许有人可以帮助我吗?

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

UPDATE: https://jsfiddle.net/j452hL2w/ here's is fiddle version of my navigation 更新: https //jsfiddle.net/j452hL2w/这是我导航的小提琴版本

I removed every onclick="javascript:location.href='#slide'" from every list item. 我从每个列表项中删除了每个onclick="javascript:location.href='#slide'" This is not necessary because you create the clickhandlers in javascript. 这不是必需的,因为您是在javascript中创建clickhandlers。

I replaced your click function with this: 我将您的点击功能替换为:

$('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');
});

Here is the updated fiddle . 这是更新的小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM