交互式JS菜单,具有流畅的显示/隐藏内容,并使用jQuery滚动到顶部

时间:2018-04-11 09:39:12

标签: javascript jquery smooth-scrolling

我在使用jQuery创建一个完全流畅的显示/隐藏和滚动菜单时遇到了麻烦 有没有比这更好的解决方案?

SEE FULL DEMO ON JSFIDDLE

JS:

$(document).ready(function(){    

    $("#showIndex1").click(function(){
        $("#index1").show(1500);
        $("#index2").hide(1500)
    });
    $("#showIndex2").click(function(){
        $("#index2").show(1500);
        $("#index1").hide(1500)
    });

   $('a[href^="#"]').on('click',function (e) {
    e.preventDefault();

    var target = this.hash;
    $target = $(target);

    $('html, body').stop().animate({
        'scrollTop':  $target.offset().top - 20

    }, 1600, 'swing', function () {
        window.location.hash = target;
        });
});

});

HTML:

<div style="width: 100px">

<a href="#indexAchor1" id="showIndex1"><h2 id="indexAchor1">index1</h2></a>
<div id="index1" style="display: none;">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>

<a href="#indexAchor2" id="showIndex2"><h2 id="indexAchor2">index2</h2></a>
<div id="index2" style="display: none;">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>

</div>

SEE FULL DEMO ON JSFIDDLE

1 个答案:

答案 0 :(得分:0)

将您的JS更改为此。

$(document).ready(function(){    
    $(".home").click(function(){
        $("#index1, #index2, #index3").hide();
    });
    $("#showIndex1").click(function(){
        $("#index1").show();
        $("#index2, #index3").hide()
    });
    $("#showIndex2").click(function(){
        $("#index2").show();
        $("#index1, #index3").hide()
    });
    $("#showIndex3").click(function(){
        $("#index3").show();
        $("#index1, #index2").hide()
    });
   $('a[href^="#"]').on('click',function (e) {
    e.preventDefault();

    var target = this.hash;
    $target = $(target);

    $('html, body').stop().animate({
        'scrollTop':  $target.offset().top

    }, 1600, function () {
        window.location.hash = target;
        });
});

});

这是fiddle

更新

fiddle