Перезагрузка скрипта при изменении размера окна
jQuery(function($) {
const article = $('.article'),
nav = $('.aside-menu'),
underheader = $('.underheader-fixed'),
underheaderHeight = underheader.outerHeight(); // получаем высоту блока
$(window).on('scroll', function () {
const position = $(this).scrollTop();
article.each(function () {
const top = $(this).offset().top - underheaderHeight - 5,
bottom = top + $(this).outerHeight();
if (position >= top && position <= bottom) {
nav.find('a').removeClass('active-scroll');
nav.find('a[href="#' + $(this).attr('id') + '"]').addClass('active-scroll');
}
});
});
nav.find('a').on('click', function () {
const id = $(this).attr('href');
$('html, body').animate({
scrollTop: $(id).offset().top - underheaderHeight
}, 1000);
return false;
});
});
*,*:before,*:after {
padding: 0;
margin: 0;
border: 0;
box-sizing: border-box;
}
h1 {font-size: 36px; margin: 0;}
.top-block {
box-sizing: border-box;
height: 3em;
border-bottom: 0.05em solid white;
background-color: blue;
position: fixed;
top: 0;
width: 100%;
z-index: 100;
}
#top-block-1 {
z-index: 101;
}
#top-block-2 {
top: 3em;
z-index: 101;
}
.underheader {
position: relative;
height: 3em;
}
.underheader-fixed {
position: fixed;
height: 6em;
top: 0;
width: 100%;
display: hidden;
}
.wrapper {
display: flex;
width: auto;
margin: 0 auto;
}
.sidebar {
width: 20%;
background-color: #e4e4e4;
padding: 2em;
}
.main-section {
width: 80%;
background-color: #e4e4e4;
padding: 0;
margin: 0;
}
.post {
position: relative;
height: 30em;
background-color: green;
}
.bw {
background-color: red;
}
.aside-menu {
background-color: #054a71;
position: sticky;
top: 8em;
border-radius: 0.5em;
border: 0.2em solid white;
box-shadow: 0 0 0.5em rgba(0,0,0,0.5);
overflow: hidden;
}
.aside-menu a {
color: white;
display: block;
padding: 1em;
text-align: center;
z-index: 10;
background-color: #054a71;
}
.aside-menu a.active-scroll,
.aside-menu a:hover {
background-color: #0172b2
}
@media (max-width: 980px) {
#top-block-2 {
display: none;
}
.underheader-fixed {
height: 3em;
}
.wrapper {
display: block;
width: auto;
}
.sidebar {
float: none;
height: auto;
width: auto;
}
.aside-menu {
margin-left: auto;
margin-right: auto;
width: inherit
}
.main-section {
width: auto;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<header class="head">
<div id="top-block-1" class="top-block"></div>
<div id="top-block-2" class="top-block"></div>
<div class="underheader" id="underheader"></div>
<div class="underheader-fixed"></div>
</header>
<main>
<section class="wrapper">
<aside class="sidebar">
<nav class="aside-menu">
<a href="#anchor-scrl-1-diseases">первый</a>
<a href="#anchor-scrl-2-diseases">второй</a>
<a href="#anchor-scrl-3-diseases">третий</a>
</nav>
</aside>
<section class="main-section">
<article class="post">
</article>
<article class="post bw article" id="anchor-scrl-1-diseases">
<h1>первый</h1>
</article>
<article class="post article" id="anchor-scrl-2-diseases">
<h1>второй</h1>
</article>
<article class="post bw article" id="anchor-scrl-3-diseases">
<h1>третий</h1>
</article>
</section>
</main>
</body>
Нужна помощь! Суть вопроса: у меня на сайте есть боковое меню, пункты которого скролят страницу к определенному якорю. При изменении размера окна, уменьшается размер шапки. Переход к якорю реализован через jquery. Чтобы верхняя часть якоря не пряталась под шапку, отступ от верха реализован через переменную, которая добавляет отступ от верхнего края соответственно размеру блока:
nav.find('a').on('click', function () {
const id = $(this).attr('href');
$('html, body').animate({
scrollTop: $(id).offset().top - underheaderHeight
}, 1000);
return false;
});
где underheaderHeight это переменная
const underheader = $('.underheader-fixed'),
underheaderHeight = underheader.outerHeight();
размер блока .underheader-fixed меняется при медиа-запросе @media (max-width: 980px). Если страницу перезагрузить, то все работает как положено, а вот если загрузить страницу и потом поменять размер окна, то страница перераспределяется соответственно медиа-запросу, а вот скрипт отрабатывает по первоначальным данным, перенося страницу со смещением.
Подскажите как правильно перезагрузить скрипт при изменении размера окна без перезагрузки всей страницы. Я нашел несколько кодов:
$(window).on("resize", function(){
if ($(window).width() > 980) {
const script = document.createElement("script");
script.type = "text/javascript";
script.src = "js/script.js";
document.getElementsByTagName("head")[0].appendChild(script);
};
});
либо путем выставления размера экрана в js и применения функции скрола внутри этой функции
window.matchMedia('(max-width: 980px)').addListener(function(e){
if(e.matches) {
//прописать функцию сюда
}
});
Но добиться желаемого результата не смог. Нужна помощь.
Ответы (2 шт):
underheaderHeight = underheader.outerHeight()
Вы находите этот размер один раз - после загрузки страницы. А нужно - внутри обработчика события.
Ошибка в том, что высоту надо узнавать после действия (после скроллинга, после клика), а у вас получается то, что вы в underheaderHeight сохраняете высоту элемента после загрузки страницы, и то не факт, так как, у вас отсутствует событие ready, рекомендую обернуть ваш код
(function($) {
$(document).ready(() => {
...
});
})(jQuery);
Значит, узнавайте высоту underheader.outerHeight() по месту, смотрите пример
jQuery(function($) {
// Тут вы нашли элемент на странице
const article = $('.article'),
nav = $('.aside-menu'),
underheader = $('.underheader-fixed');
$(window).on('scroll', function () {
let underheaderHeight = underheader.outerHeight(); // получаем высоту блока
const position = $(this).scrollTop();
article.each(function () {
const top = $(this).offset().top - underheaderHeight - 5,
bottom = top + $(this).outerHeight();
if (position >= top && position <= bottom) {
nav.find('a').removeClass('active-scroll');
nav.find('a[href="#' + $(this).attr('id') + '"]').addClass('active-scroll');
}
});
});
nav.find('a').on('click', function () {
let underheaderHeight = underheader.outerHeight(); // получаем высоту блока
const id = $(this).attr('href');
$('html, body').animate({
scrollTop: $(id).offset().top - underheaderHeight
}, 1000);
return false;
});
});