Как сделать плавную навигацию которая будет подсвечивать место на котором находится пользователь?
Есть такая плавная навигация по странице. Как сделать чтобы в навигационном меню добавлялся класс "current" в зависимости от места на котором сейчас находится пользователь? Чтобы когда человек постепенно крутил мышку, ему отображался раздел сайта в навигационном меню.
$(document).ready(function(){
$('a[href^="#"]').bind('click.smoothscroll',function (e) {
e.preventDefault();
let target = this.hash,
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing', function () {
window.location.hash = target;
});
});
});
body {
padding: 0 4em;
margin: 0;
font: 14px/1.8 Helvetica;
color: #444;
}
a {
text-decoration: none;
}
/* = Стили для контента */
#main {
width: 75%;
}
h2 {
font-size: 1.8em;
border-bottom: 1px solid #444;
position: relative;
}
p {
height: 100vh;
}
/* = Стили для ссылки наверх */
h2 a {
position: absolute;
bottom: 0;
right: 0;
padding: 0 10px;
font-size: 11px;
color: #fff;
background: #444;
display: block;
}
/* = Стили для содержания */
aside {
display: block;
width: 20%;
position: fixed;
left: 78%;
top: 50%;
}
li {
list-style: square;
color: #006600;
}
li a {
font: bold italic 16px Helvetica;
color: #006600;
}
li a:hover {
color: #990000;
}
.current {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main">
<h2 id="one">One</h2>
<p>Тут текст Lorem Ipsum</p>
<h2 id="two">Two</h2>
<p>Тут текст Lorem Ipsum.</p>
<h2 id="three">Three</h2>
<p>Тут текст Lorem Ipsum</p>
<h2 id="four">Four</h2>
<p>Тут текст Lorem Ipsum</p>
<h2 id="five">Five</h2>
<p>Тут текст Lorem Ipsum</p>
<h2 id="six">Six</h2>
<p>Тут текст Lorem Ipsum</p>
</div>
<aside>
<ul>
<li><a class="current" href="#one">One</a></li>
<li><a href="#two">Two</a></li>
<li><a href="#three">Three</a></li>
<li><a href="#four">Four</a></li>
<li><a href="#five">Five</a></li>
<li><a href="#six">Six</a></li>
</ul>
</aside>
Ответы (1 шт):
Автор решения: Neakit
→ Ссылка
Примерно так:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body {
padding: 0 4em;
margin: 0;
font: 14px/1.8 Helvetica;
color: #444;
}
a {
text-decoration: none;
}
/* = Стили для контента */
#main {
width: 75%;
}
h2 {
font-size: 1.8em;
border-bottom: 1px solid #444;
position: relative;
}
p {
height: 100vh;
}
/* = Стили для ссылки наверх */
h2 a {
position: absolute;
bottom: 0;
right: 0;
padding: 0 10px;
font-size: 11px;
color: #fff;
background: #444;
display: block;
}
/* = Стили для содержания */
aside {
display: block;
width: 20%;
position: fixed;
left: 78%;
top: 50%;
}
li {
list-style: square;
color: #006600;
}
li a {
font: bold italic 16px Helvetica;
color: #006600;
}
li a:hover {
color: #990000;
}
.current {
color: red;
}
</style>
<script src="https://rawgit.com/kimmobrunfeldt/progressbar.js/1.0.0/dist/progressbar.js"></script>
<link href="https://fonts.googleapis.com/css?family=Raleway:400,300,600,800,900" rel="stylesheet" type="text/css">
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/lodash/4.10.0/lodash.js"></script>
<div id="main">
<h2 id="one">One</h2>
<p>Тут текст Lorem Ipsum</p>
<h2 id="two">Two</h2>
<p>Тут текст Lorem Ipsum.</p>
<h2 id="three">Three</h2>
<p>Тут текст Lorem Ipsum</p>
<h2 id="four">Four</h2>
<p>Тут текст Lorem Ipsum</p>
<h2 id="five">Five</h2>
<p>Тут текст Lorem Ipsum</p>
<h2 id="six">Six</h2>
<p>Тут текст Lorem Ipsum</p>
</div>
<aside>
<ul>
<li><a id="one" href="#one" class="current">One</a></li>
<li><a id="two" href="#two">Two</a></li>
<li><a id="three" href="#three">Three</a></li>
<li><a id="four" href="#four">Four</a></li>
<li><a id="five" href="#five">Five</a></li>
<li><a id="six" href="#six">Six</a></li>
</ul>
</aside>
<script>
$(document).ready(function(){
$('a[href^="#"]').bind('click.smoothscroll',function (e) {
e.preventDefault();
let target = this.hash, $target = $(target);
$('html, body').stop().animate({ 'scrollTop': $target.offset().top }, 900, 'swing', function () {
window.location.hash = target;
});
});
// устанавливает класс current активной странице
function setActiveClass (id) {
$( "a" ).each(function( index ) {
$( this ).removeClass( "current" )
});
$( `a#${id}` ).addClass( "current" )
}
// получение позиций "страниц"
function getSectionCurrentPositions () {
const sectionsIds = [ 'one', 'two', "three", "four", "five", "six" ];
return sectionsIds.map(id => {
const offset = $(`#${id}`).offset().top;
return {
id: id,
offset: parseInt(offset)
};
})
}
const positionsOffset = getSectionCurrentPositions();
// обработчик события скрола на странице
// механику можете прописать свою
function scrollHandler () {
const scrollOffset = $(document).scrollTop();
let currentPageId = positionsOffset[0].id;
if(scrollOffset <= positionsOffset[0].offset) {
currentPageId = positionsOffset[0].id;
} else if(scrollOffset >= positionsOffset[positionsOffset.length - 1].offset) {
currentPageId = positionsOffset[positionsOffset.length - 1].id;
} else {
let currentPage = positionsOffset.find((el, index, array) => {
return el.offset <= scrollOffset && scrollOffset < array[index + 1].offset;
});
currentPageId = currentPage.id;
}
console.log('currentPageId', currentPageId);
setActiveClass(currentPageId);
}
// debounce чтобы не дергать функцию при каждом собитии скрола
$(document).on("scroll", _.debounce(scrollHandler, 250));
});
</script>
</body>
</html>