簡體   English   中英

平滑滾動插件未設置活動狀態(JS修改)

[英]Active state not being set by smooth-scroll plugin (JS modification)

我在使用腳本時遇到了麻煩,該腳本可以平滑滾動以及主導航上的活動狀態。 插件: http//tinyurl.com/amz4kob

請注意,導航欄是固定的,因此實際上沒有高度。

我有兩個似乎無法克服的問題:

  1. 在頁面加載時,活動狀態將應用於聯系鏈接。 如果向下滾動1像素,則活動狀態將正確地應用於主鏈接。
  2. 我一輩子都無法弄清楚如何修改腳本來注意具有特定ID的元素中的錨點? 即我只希望此腳本將活動狀態應用於標簽中的元素。

任何幫助將不勝感激。

@rrfive

為了使生活更輕松,這里是帶注釋的腳本:

$(document).ready(function() {
//Get Sections top position
function getTargetTop(elem){

    //gets the id of the section header
    //from the navigation's href e.g. ("#html")
    var id = elem.attr("href");

    //Height of the navigation
    var offset = 0;

    //Gets the distance from the top and subtracts the height of the nav.
    return $(id).offset().top - offset;
}

//Smooth scroll when user click link that starts with #
$('a[href^="#"]').click(function(event) {

    //gets the distance from the top of the section refenced in the href.
    var target = getTargetTop($(this));

    //scrolls to that section.
    $('html, body').animate({scrollTop:target}, 500);

    //prevent the browser from jumping down to section.
    event.preventDefault();
});

//Pulling sections from main nav.
var sections = $('a[href^="#"]');

// Go through each section to see if it's at the top.
// if it is add an active class
function checkSectionSelected(scrolledTo){
    //How close the top has to be to the section.
    var threshold = 54;

    var i;

    for (i = 0; i < sections.length; i++) {

        //get next nav item
        var section = $(sections[i]);

        //get the distance from top
        var target = getTargetTop(section);

        //Check if section is at the top of the page.
        if (scrolledTo > target - threshold && scrolledTo < target + threshold) {
            sections.removeClass("active");
            section.addClass("active");
        }
    };
}

//Check if page is already scrolled to a section.
checkSectionSelected($(window).scrollTop());

$(window).scroll(function(e){
    checkSectionSelected($(window).scrollTop())
});

});

您使用的插件會檢查<div class="section"></div>元素在頁面上的位置,但是因為您已將它們display:none; ,則所有部分都從頁面頂部返回“ 0像素”,並且由於“接觸”部分是頁面的最后一個,因此它就在那里停止了。

因此,只需刪除display:none; 從CSS中的.section ,它將可以正常工作。

.section {
    /*display: none; <-- Comment this line out. */
    height: 100%;
    min-width: 990px;
}

暫無
暫無

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

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