javascript - li元素的平滑滚动onclick

标签 javascript jquery html

我正在尝试编写 jQuery 代码,该代码将使页面滚动到 div,而不是立即转到那里,并使其尽可能简单。我已将所需 div 的 id 添加到 li 元素。

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

更新: https://jsfiddle.net/j452hL2w/这是我的导航的 fiddle 版本

最佳答案

我从每个列表项中删除了每个 onclick="javascript:location.href='#slide'"。这不是必需的,因为您是在 JavaScript 中创建点击处理程序的。

我用这个替换了你的点击函数:

$('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 .

关于javascript - li元素的平滑滚动onclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37515651/

相关文章:

javascript - 当脚本选择单选按钮时,paper-radio-group-changed 不触发

javascript - 带百分比的 JQuery Ajax 请求

javascript - 如何在 JSON 字符串中包含 Javascript 字符串构造函数?

PHP 绕过 jQuery 代码

JavaScript 闭包 __proto__

jquery - 页脚高度 100% 在垂直居中的页面上

javascript - 有没有更好的方法来防止单击 href 时整个页面滚动?

javascript - 缓存 HTML 字符串或 DOM 元素?

javascript - 在所需行设置文本区域的值

javascript - Polymer.js 双向绑定(bind)到 textarea 值