Навигационные ссылки должны быть активными для определенного раздела при прокрутке - PullRequest
0 голосов
/ 24 апреля 2020

У меня был многостраничный сайт, в котором есть четыре ссылки на панели навигации. Из четырех ссылок две ссылки перенаправляют на другие новые страницы. Есть раздел контента, связанный с теми ссылками, которые есть на моей целевой странице. Я хотел бы, чтобы те тоже. Пожалуйста, помогите в этой ситуации код, который я реализовал до сегодняшнего дня

<link href='https://fonts.googleapis.com/css?family=Lato:100,400,700' rel='stylesheet' type='text/css'>

<nav class="navigation" id="mainNav">
            <a class="navigation__link" href="#1">home</a>
            <a class="navigation__link" href="#2">about</a>
            <a class="navigation__link" href="test.html">test</a>
            <a class="navigation__link" href="#test1.html">test1</a>
</nav>

<div class="page-section home" id="1">
            <h1>Smooth scroll, fixed jump menu with active class</h1>
</div>
<div class="page-section about" id="2">
            <h1>Section Two</h1>
</div>
<div class="page-section" id="3">
            <h1>Section Three</h1>
</div>
<div class="page-section" id="4">
            <h1>Section Four</h1>
</div>
<div class="page-section test" id="5">
            <h1>Section Five</h1>
</div>
<div class="page-section test1" id="6">
            <h1>Section Six and this section is test section</h1>
</div>
<div class="page-section" id="7">
            <h1>Section Seven and this section is test1</h1>
</div>


* { 
    font-family: 'Lato', sans-serif;
    font-weight: 300;
    transition: all .1s ease; 
}

html, body {
        height: 100%;
}

h1 { font-size: 64px; }

.page-section {
        height: 480px;
        width: 50%;
        margin-left: 35%;
        margin-top: 5%;
        padding: 3em;
    background: linear-gradient(45deg, #43cea2 10%, #185a9d 90%);
        color: white;
        box-shadow: 0px 3px 10px 0px rgba(0,0,0,0.5);
}

.navigation {
    position: fixed; 
        width: 30%;
        margin-left: 2%;
    background-color: #999;
    color: #fff;

    &__link {
            display: block;
        color: #ddd; 
        text-decoration: none;
        padding: 1em;
            font-weight: 400;

            &:hover {
                background-color: #aaa;
            }

           &.active {
            color: white;
                 background-color: rgba(0,0,0,0.1);
           }
    }
}


$(document).ready(function() {
        $('a[href*=#]').bind('click', function(e) {
                e.preventDefault(); // prevent hard jump, the default behavior

                var target = $(this).attr("href"); // Set the target as variable

                // perform animated scrolling by getting top-position of target-element and set it as scroll target
                $('html, body').stop().animate({
                        scrollTop: $(target).offset().top
                }, 600, function() {
                        location.hash = target; //attach the hash (#jumptarget) to the pageurl
                });

                return false;
        });
});

$(window).scroll(function() {
        var scrollDistance = $(window).scrollTop();

        // Show/hide menu on scroll
        //if (scrollDistance >= 850) {
        //      $('nav').fadeIn("fast");
        //} else {
        //      $('nav').fadeOut("fast");
        //}

        // Assign active class to nav links while scolling
        $('.page-section').each(function(i) {
                if ($(this).position().top <= scrollDistance) {
                        $('.navigation a.active').removeClass('active');
                        $('.navigation a').eq(i).addClass('active');
                }
        });
}).scroll()

Ответы [ 2 ]

1 голос
/ 24 апреля 2020

То, что вы ищете, это прокрутка. См .:

Scrollspy · Bootstrap

или, если это вам не подходит, просто Google "scrollspy" и найти другие платформы, которые могут подходит вам больше.

0 голосов
/ 24 апреля 2020

Для дополнительных пользовательских назначений того, что должно произойти, есть (очень старый, но все еще работающий) плагин jQuery. См .:

Github: jquery .inview
Учебное пособие: Элемент «в поле зрения» Плагин событий

Использование:

$('#mySection1').on('inview', function(event, isInView) {
  if (isInView) {
    $('#myNavOption1').addClass('active');
  } else {
    $('#myNavOption1').removeClass('active');
  }
});
...