0

谁能告诉我如何编辑此代码,使其适用于所有具有“enablescroll”类的锚链接,然后滚动到它们各自的目标ID?

现在我有:

<script>
$(document).ready(function() {
    $('.enablescroll').click(function(){  //when links with class "enablescroll" clicked
        $('.pagecontainer').animate({  //animate this container not the viewport
            scrollTop: $("#target").offset().top  //scroll to the div with id "target"
        }, 1000);
    });
});
</script>

这显然只有在我有 1 个名为“target”的滚动目标时才有效。但我有 50 个链接,每个链接都有不同的目标 ID,如下所示:

<div class="pagecontainer">

<a href="#section1" class="enablescroll">Section 1</a>
<a href="#section2" class="enablescroll">Section 2</a>
<a href="#section3" class="enablescroll">Section 3</a>
<a href="#section4" class="enablescroll">Section 4</a>
<a href="#section5" class="enablescroll">Section 5</a>

....

<div id="section1">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eros ipsum, ullamcorper in tincidunt ut, fringilla vel risus. Cras purus arcu, vulputate eu tempus sit amet, gravida et diam. Nulla commodo aliquam metus.</div>

<div id="section2">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eros ipsum, ullamcorper in tincidunt ut, fringilla vel risus. Cras purus arcu, vulputate eu tempus sit amet, gravida et diam. Nulla commodo aliquam metus.</div>

<div id="section3">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eros ipsum, ullamcorper in tincidunt ut, fringilla vel risus. Cras purus arcu, vulputate eu tempus sit amet, gravida et diam. Nulla commodo aliquam metus.</div>

<div id="section4">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eros ipsum, ullamcorper in tincidunt ut, fringilla vel risus. Cras purus arcu, vulputate eu tempus sit amet, gravida et diam. Nulla commodo aliquam metus.</div>

<div id="section5">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eros ipsum, ullamcorper in tincidunt ut, fringilla vel risus. Cras purus arcu, vulputate eu tempus sit amet, gravida et diam. Nulla commodo aliquam metus.</div>

</div>

如何获取每个链接的目标,然后将它们分配给该滚动脚本?我记得语法是这样的:

$(this.getAttribute("href"))

但我不知道其余的语法如何。

谢谢。

4

0 回答 0