簡體   English   中英

活動班級的平滑滾動導航

[英]smooth scroll navigation with active class

我一直在為網站使用平滑滾動導航欄。 我設法使導航欄滾動到HTML文檔中的不同部分,並且我一直在嘗試根據您所在網頁的部分使導航欄鏈接變為活動狀態。

在玩完代碼之后,我不知道該怎么做。 我需要做什么?

這是我的代碼:

 $('#navbar li').click(function() { $(this).addClass('active').siblings('li').removeClass('active'); }); 
 @import url(https://fonts.googleapis.com/css?family=Maven+Pro:400,900,700,500); html{ font-family: 'Maven Pro', sans-serif; } body{ background:fixed url(images/bright_squares.png) #cccccc; position:relative; padding:0; margin:0; } #home {padding-top:50px;height:500px;color: #fff; background-image:url(images/random_grey_variations.png);} #about {padding-top:50px;height:500px;color: #fff;} #portfolio {padding-top:50px;height:500px;color: #fff;} #contact {padding-top:50px;height:500px;color: #fff;} background-dark{ background:fixed url(images/random_grey_variations.png); } #navbar { position:fixed; top: 0px; left: 0px; right: 0px; height: 60px; margin: 0; padding: 0; list-style: none; background: #222; font-family: 'Maven Pro', sans-serif; font-size: 18px; font-weight: 300; } #navbar li { position: relative; float: left; line-height: 60px; background: inherit; text-align: center; transition: all .2s; } #navbar li a { position: relative; display: block; padding: 0 20px; line-height: inherit; color: white; text-decoration: none; } #navbar li:before { content: ''; display: block; position: absolute; left: 50%; margin-left: -30px; width: 60px; height: 60px; background: #222; border-radius: 50%; transform: rotate(45deg); transition: all 0, background .2s; } #navbar li:hover:before { margin-top: 1px; border-radius: 50% 50% 0 50%; transition: all .1s, background .2s, margin-top .2s cubic-bezier(.5,30,.2,0); } #navbar li:hover, #navbar li:hover:before { background: #3a3a3a; } #navbar li.active, #navbar li.active:before { background: steelblue; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <ul id="navbar"> <li class="active"><a href="#">Home</a></li> <li><a href="#about">About</a></li> <li><a href="#portfolio">Portfolio</a></li> <li><a href="#contact">Contact</a></li> </ul> <div id="home"> <h1>Welcome</h1> <p>Test</p> </div> <div id="portfolio"> <h1>portfolio</h1> <p>Test</p> </div> <div id="contact"> <h1>contact</h1> <p>Test</p> </div> <div id="about"> <h1>About Me</h1> <p>Test</p> </div> 

我認為這可能會回答您的問題。 只需將此代碼添加到您已有的click函數中即可。

$($(this).children().attr('href')).addClass('selected').siblings('div').removeClass('selected');

您需要將home鏈接更改為#home而不是#

如果您想放棄所有這些,這是更快的版本。

<script>
    $('#navbar li').click(function() {
        $(this).addClass('active').siblings('li').removeClass('active');
        var x = $($(this).children().attr('href')).first().offset().top
        $('body').animate({
          scrollTop: x
        }, 2000);
    });
</script>

這將添加我認為您正在尋找的滾動動畫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM