按下按钮,Jquery向下滚动到每个部分的顶部

时间:2014-07-03 09:56:38

标签: javascript jquery html css

这是我的代码:Js Fiddle

正如你所看到的,我有几个部分在彼此之上,高度为100%。我想知道如何获得它,所以当用户点击“了解更多”时,他们会滚动到下一部分,因此该部分的顶部位于页面顶部。

通常我会这么做很简单:

$('body').animate({
scrollTop:$(document).height()
});

但是,如果用户已经在部分中间向下滚动然后点击按钮,则无效。如果我可以为每个按钮使用相同的功能,而不是具有三个不同的功能,每个不同的部分一个,这也是很好的。

我猜代码就像(伪):scroll to top sectiona + 1

5 个答案:

答案 0 :(得分:2)

使用jQuery和平滑滚动

 $('a').click(function(){
        var nextSection = $(this).closest('section').next('section');
        $('html, body').animate({
            scrollTop: $(nextSection).offset().top
        }, 2000);
    });

答案 1 :(得分:0)

为什么不将id传递给每个部分,并且在href中引用该ID,如

<section id="sectionOne">
  <a href="#sectionTwo">Move to section two</a>
</section>

<section id="sectionTwo">
  <a href="#sectionOne">Move to section one</a>
</section>

答案 2 :(得分:0)

您还可以尝试以下操作。

var amount_to_scroll_by = $(document).scrollTop() + element_to_scroll.getBoundingClientRect().top);

$(document).scrollTop(amount_to_scroll_by); // animate this scroll

希望这会有所帮助:)

答案 3 :(得分:0)

使用jquery,您可以顺利滚动到目标。

这是SAMPLE

JS:

$("a").click(function(e) {
    e.preventDefault();
    var target = $(this).attr('href');   
    $('html, body').animate({ scrollTop : $(target).offset().top + "px"});    
});

答案 4 :(得分:0)

您应首先修复锚点并使用哈希片段以允许锚点之间的本地导航。

我已经创建了一个非常简单的演示,供您理解(不使用您的标记来保持简单)。

演示:http://jsfiddle.net/abhitalks/9uxGq/15/

(标记的另一个演示:http://jsfiddle.net/abhitalks/9uxGq/19/

您需要两个锚点,一个用作点击链接,另一个用于标记目标作为锚点的位置。

例如

<div>
    <a id="LearnMore1"></a> <!-- Used for marking the anchor with hash fragment -->
    <h2>Sub Heading 2</h2>
    <p>
        Some text content here
    </p>
    <a href="#LearnMore2">Learn More</a> <!-- Used to click to got to next anchor -->
</div>

注意 :当然不是使用第二个锚作为标记,而是使用div(或者在您的情况下sectionid。但是,a更好,因为它对内容导航更具语义性,它意味着

一旦完成,这将成为您的后备。现在,您可以使用jQuery等轻松实现动画。

这很简单:

// bind click on anchors (use selectors as per your requirements)
$("a").on("click", function(e) { 
    e.preventDefault(); // prevent the default behaviour
    var nextAnchor = this.hash.replace("#", ""); // get the next marker anchor 
    var gotoPoint = $("#" + nextAnchor).position().top; // get the position of marker
    $('body').animate({ scrollTop: gotoPoint }, 'normal'); // animate the body
});

可替换地:

// bind click on anchors (use selectors as per your requirements)
$("a").on("click", function(e) { 
    e.preventDefault(); // prevent the default behaviour
    var nextAnchor = $(this).attr('href'); // get the next marker anchor 
    var gotoPoint = $(nextAnchor).position().top; // get the position of marker
    $('body').animate({ scrollTop: gotoPoint }, 'normal'); // animate the body
});

现在将此应用于您的用例,演示将变为: http://jsfiddle.net/abhitalks/9uxGq/19/

希望有所帮助,您可以在标记和用例中使用它。