Jquery根据数据属性滚动到部分

时间:2015-02-16 08:42:48

标签: javascript jquery html

我试图制作这些图片,当您点击它们时,它们会滚动到data-down属性中给出的ID。但是,当我尝试它时,它不会sc。当您对包含要滚动到的ID的变量执行控制台日志时,它是正确的,因此我不知道它为什么不起作用。

<header>
    <div id="header-content">
        <h1>Welcome to the JETS Lake Garda Campaign</h1>
        <img class="down" data-down="#about" src="images/down.png">
    </div>
</header>
<section id="about">
    <h2>About Us</h2>
    <p>Libero minus dicta, sapiente, dolor, quidem quisquam magnam expedita eos voluptates saepe itaque maiores facilis sit nihil consequuntur vero hic possimus inventore autem. Voluptate amet dicta corporis dolorum facilis, quisquam.</p>
    <img class="down" data-down="#sailors" src="images/down.png">
</section>
<section id="sailors">
    <h2>Sailors</h2>
    <p>Libero minus dicta, sapiente, dolor, quidem quisquam magnam expedita eos voluptates saepe itaque maiores facilis sit nihil consequuntur vero hic possimus inventore autem. Voluptate amet dicta corporis dolorum facilis, quisquam.</p>
    <div class="down" data-down="#sponsors" src="images/down.png">
</section>
<section id="sponsors">
    <h2>Sponsors</h2>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quasi, itaque, pariatur. Aliquam ab in, ullam nostrum quis eos, commodi at? Eos quod amet dignissimos dolorum consequuntur adipisci dolore ducimus quis.</p>
</section>
$(document).ready(function () {
    $('.down').on('click', function () {
        var toGo = $(this).data('down');
        console.log(toGo);
        $('html,body').animate({
            scrollTop: $(toGo).offset.top
        }, 'slow');
    });
});

http://jsfiddle.net/8bc15bdu/

4 个答案:

答案 0 :(得分:2)

您必须将$(toGo).offset.top替换为$(toGo).offset().top

答案 1 :(得分:0)

offset是一个函数,因此您应该像这样访问它:

$(document).ready(function() {

  // Navigation buttons

  $('.down').on('click', function(){
    var toGo = $(this).data('down');
    $('html,body').animate({
      scrollTop: $(toGo).offset().top
    }, 'slow');

  });

});

Here是一个更新的工作示例。

答案 2 :(得分:0)

$(toGo).offset.top替换为$(toGo).offset().top

答案 3 :(得分:0)

您可以尝试使用“scrollTo”jQuery扩展。我在几个项目中使用它,它很容易实现和调试:)

https://github.com/flesler/jquery.scrollTo