0

我正在尝试制作一个简单的菜单,每个 li 标签在单击时使用 scrollTop 进行导航。

<div class="menu" id="menu1">
   <ul>
    <li class="button1">Section1</li>
    <li class="button2">Section2</li>
    <li class="button3">Section3</li>
    <li class="button4">Section4</li>
    <li class="button5">Section5</li>
   </ul>
</div>

$(".button1").click(function() {

    $('html, body').animate({
        scrollTop: $('.section1').offset().top-55
    });
}); 

问题是我有几个部分需要使用相同的逻辑但应用于不同的部分,所以主要我不想为每个部分编写单独的代码,而是应用到每个菜单的代码可以为我解决这个问题。我知道有很多问题要问,但我对此很陌生。

4

1 回答 1

0

Use a common class on each of your <li> elements. I see you have classes now, however they are unique, these should probably be ID's. A common class they could share for example is menuButton, then your function could be:

$(".menuButton").click(function() {
    //var elementID = this.id <--Optional variable containing the clicked element ID

    //Sample logic
    //if (elementID == "button1") { animate this way } )
    $('html, body').animate({
        scrollTop: $('.section1').offset().top-55
    });
}); 

Modified HTML:

<div class="menu" id="menu1">
    <ul>
        <li id="button1" class="menuButton">Section1</li>
        <li id="button2" class="menuButton">Section2</li>
        <li id="button3" class="menuButton">Section3</li>
        <li id="button4" class="menuButton">Section4</li>
        <li id="button5" class="menuButton">Section5</li>
    </ul>
</div>
于 2013-07-02T22:39:03.790 回答