繁体   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