На сайте есть несколько разделов. Первый с картинкой, на нем шапка должна быть прозрачной. Следующие блоки цветные и на них шапка должна принимать цвет блока. Как мне этого добиться? Я написал код на JQuery, чтобы шапка менялась с прозрачной на цвет второго блока, но вот мне кажется есть решение получше, чем писать так для каждого блока, однако я не могу его найти…
Код:
JS:
$(function() {
let header = $('.header'),
intro = $('.intro');
$(window).scroll(function() {
if($(this).scrollTop() > intro.outerHeight()) {
header.addClass('header_filled');
} else {
header.removeClass('header_filled');
}
});
});
CSS:
*,
*::before,
*::after {
box-sizing: border-box;
}
h1, h2, h3, h4, h5, h6 {
margin: 0;
}
a {
text-decoration: none;
}
body {
margin: 0;
font-family: 'Montserrat', sans-serif;
font-size: 15px;
line-height: 1.6;
color: #fff;
}
/* Animations */
/* Container */
.container {
width: 100%;
max-width: 1200px;
margin: 0 auto;
}
/* Header */
.header {
width: 100%;
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 100;
}
.header__logo {
font-size: 30px;
font-weight: 700;
color: #fff;
}
.header__inner {
display: flex;
justify-content: space-between;
align-items: center;
}
.header_filled {
background-color: #3ebb46;
border-radius: 0 0 20px 20px;
transition: .2s ease-in;
}
/* Intro */
.intro {
display: flex;
flex-direction: column;
justify-content: center;
width: 100%;
height: 100vh;
background: url("../img/intro.jpg") center no-repeat;
background-size: cover;
font-size: 20px;
}
.intro__inner {
margin: 0 auto;
backdrop-filter: blur(2px);
-webkit-backdrop-filter: blur(2px);
border: 1px solid #fff;
border-radius: 30px;
}
.intro__title {
font-size: 72px;
text-align: center;
}
.intro__subtitle {
font-family: 'Jost', sans-serif;
text-transform: uppercase;
font-size: 36px;
text-align: center;
}
/* Navigation */
.nav {
display: flex;
font-size: 15px;
font-weight: 500;
text-transform: uppercase;
}
.nav__link {
color: #fff;
padding: 0 10px;
}
.nav__link:hover {
color: #ffffff;
background-color: #0d7711;
border-radius: 10px;
}
/* About */
.about {
background-color: #3ebb46;
width: 100%;
height: 100vh;
padding: 60px 0;
color: #fff;
font-size: 20px;
}
.about__title {
background-color: #61c467;
text-align: center;
border-radius: 10px;
}
.about__text {
text-align: justify;
}
.about__link {
font-size: 21px;
font-weight: 700;
color: #6868d8;
text-decoration: wavy;
padding:0 2px 0 2px;
}
.about__link:hover {
text-decoration: none;
color: #3ebb46;
background-color: #fff;
border-radius: 5px;
transition: .1s ease-in;
}
/* Servives */
.services {
background-color: #48daae;
width: 100%;
height: 100vh;
padding: 60px 0;
color: #fff;
font-size: 20px;
}
HTML:
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/normalize.css">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;700&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Jost&display=swap" rel="stylesheet">
<script src="js/jquery-3.6.0.min.js"></script>
<script src="js/scripts.js"></script>
<title>Document</title>
</head>
<body>
<header class="header" id="header">
<div class="container">
<div class="header__inner" id="header" >
<a href="#main"><div class="header__logo">CottageKarelia</div></a>
<nav class="nav">
<a class="nav__link" href="#main">Главная</a>
<a class="nav__link" href="#about">О компании</a>
<a class="nav__link" href="#services">Услуги</a>
<a class="nav__link" href="#">Отдых в Карелии</a>
<a class="nav__link" href="#">Владельцам</a>
<a class="nav__link" href="#">Оплата</a>
<a class="nav__link" href="#">Контакты</a>
</nav>
</div>
</div>
</header>
<div class="intro" id="main">
<div class="container">
<div class="intro__inner">
<h1 class="intro__title">Гостевые дома и коттеджи Карелии</h1>
<br>
<h2 class="intro__subtitle">Простой выбор для Вашего отдыха!</h2>
</div>
</div>
</div>
<section class="about" id="about">
<div class="container">
<div class="about__title">
<h1>О деятельности компании</h1>
</div>
<div class="about__text">
<p>
Наш сайт является крупнейшим <a class="about__link" href="catalog.html">каталогом</a> гостевых домов и коттеджей в Карелии,
на котором собрано более 1000 позиций. Здесь Вы сможете найти любой дом,
соответствующий всем Вашим потребностям. Благодаря удобной форме поиска,
Вы наиболее полно сможете охарактеризовать, что именно Вам необходимо, после чего,
Вам будут представлены наиболее подходящие дома. Когда Вы определитесь с выбором дома,
Вам будет предложено забронировать его, после чего и начнется Ваш отдых! Кроме того,
мы с радостью предлагаем гостям Карелии различные <a href="tours.html" class="about__link">туры</a>, созданные для абсолютно любой
категории людей.
</p>
<p>
Наши менеджеры свяжутся с Вами и узнают все Ваши пожелания, после чего они сформируют Вам тур:
определят наиболее предпочтительные и удобные варианты проезда, сообщат о дополнительных возможностях
на территории выбранного места или тура, посоветуют достопримечательности Карелии, которые можно будет
посетить неподалеку от выбранного дома, предложат Вам трансфер с вокзала к гостевому дому или коттеджу
и обратно. Иными словами, за Вас сделают все и обеспечат Вам лучший отдых на земле в райском уголке,
по имени Карелия!
</p>
</div>
</div>
</section>
<section class="services" id="services">
<div class="container">
<div class="services__title">
<h1>Дополнительные услуги</h1>
</div>
</div>
</section>
</body>
</html>
I am trying to do a nice effect when the header leaves the current block. I want the background color and the color of the text to change when scrolling down.
html:
<header class="green">Logo</header>
<header class="red">Logo</header>
<section id='content1'>
<h1>Content</h1>
<p>Goes here!</p>
</section>
<section id='content2'>
<h1>Content</h1>
<p>Goes here!</p>
</section>
css:
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
header {
width: 100%;
position: fixed;
display: block;
top: 0;
font-size: 20pt;
padding: 15px 10px
}
.green {
background: green;
color: #000;
z-index: 2
}
.red {
background: red;
color: #fff;
z-index: 1
}
section {
position: relative;
height: 500px;
padding: 100px 10px
}
#content1 {
background: #D9D9D9;
z-index: 1
}
#content2 {
background: #9FDAD0;
z-index: 2
}
An example serves best, something like this https://www.dropbox.com/
Thanks!
asked Nov 15, 2018 at 17:17
7
So i redid it with some Javascript.
This effect is awesome, feel free to improve it if you like!
Is this possible to accomplish without Javascript?
const secondBlock = document.getElementById('content2')
const header = document.getElementsByTagName('header')
const headerHeight = 61
function setHeader () {
const scrollPoint = window.pageYOffset + headerHeight
let blockPoint = 61 - (scrollPoint - secondBlock.offsetTop)
if (blockPoint <= 0) { blockPoint = 0 }
if (scrollPoint > secondBlock.offsetTop) {
header[0].style = `max-height: ${blockPoint}px;`
} else {
header[0].style = `max-height: ${headerHeight}px;`
}
window.requestAnimationFrame(setHeader)
}
window.requestAnimationFrame(setHeader)
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
header {
display: block;
font-size: 20pt;
height: 61px;
line-height: 61px;
padding-left: 10px;
position: fixed;
top: 0;
width: 100%;
}
header#first {
background: #8292C3;
color: #000;
overflow: hidden;
z-index: 10;
}
header#second {
background: #82C3B9;
color: #fff;
z-index: 9;
}
section {
height: 500px;
padding: 100px 10px;
position: relative;
}
#content1 {
background: #96A6D5;
}
#content2 {
background: #99D6CC;
}
<header id='first'>Logo - <small>scroll down to see the magic!</small></header>
<header id='second'>Logo - <small>scroll down to see the magic! COOL!</small></header>
<section id='content1'>
<h1>Content</h1>
<p>Goes here!</p>
</section>
<section id='content2'>
<h1>Content</h1>
<p>Goes here!</p>
</section>
answered Nov 15, 2018 at 19:41
LonniELonniE
992 silver badges9 bronze badges
The smooth transition you’re looking for can be done in CSS, but you’ll need some JavaScript in order to initiate the animation.
window.onscroll = function(){
var top = window.scrollY;
console.log('Top: ' + top);
var header = document.getElementsByTagName('header');
var offset = header.innerHeight; //changed offset to be dynamic, so it works on mobile screens.
if(top > offset){
header[0].classList.remove('top');
header[0].classList.add('scrolled');
} else {
header[0].classList.remove('scrolled');
header[0].classList.add('top');
}
};
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
position: relative;
}
header {
width: 100%;
position: fixed;
height: 75px;
display: block;
top: 0;
z-index: 100;
font-size: 20pt;
padding: 15px 10px
}
header.top {
background: #222;
color: #fff;
transition: all 0.3s ease;
}
header.scrolled {
background: #555;
color: #e0e0e0;
transition: all 0.3s ease;
}
.green {
background: green;
color: #000;
z-index: 2
}
.red {
background: red;
color: #fff;
z-index: 1
}
section {
position: relative;
height: 800px;
padding: 100px 10px
}
#content1 {
background: #D9D9D9;
z-index: 1
}
#content2 {
background: #9FDAD0;
z-index: 2
}
<header class="top">Logo</header>
<section id='content1'>
<h1>Content</h1>
<p>Goes here!</p>
</section>
<section id='content2'>
<h1>Content</h1>
<p>Goes here!</p>
</section>
This basically says that when we scroll passed the height of the header (in this case 50px), remove the «top» class from it, and add the «scrolled» class from it. You can use the css selectors header.top
and header.scrolled
to do your transition animations. Be sure to use transition: background-color (time) (timing function), color (time) (timing function);
to achieve the smoothness you’re looking for.
answered Nov 15, 2018 at 17:38
RyanRyan
4362 silver badges10 bronze badges
2
You can change it with the class. Like i use this website.
http://www.moumaachi.com/
it has class like this
<div class="header-v2 navbar-fixed-top">
but when scroll down to 50 px then it will showa this
<div class="header-v2 navbar-fixed-top top-nav-collapse">
and normal it has
<div class="thiswillhide">
but when scroll down more then it wil like this
<div class="thiswillhide hidesearch">
you can use this code
<script>
//jQuery to collapse the navbar on scroll
$(window).scroll(function() {
if ($(".header-v2").offset().top > 50) {
$(".navbar-fixed-top").addClass("top-nav-collapse");
} else {
$(".navbar-fixed-top").removeClass("top-nav-collapse");
}
if ($(".header-v2").offset().top > 600) {
$(".thiswillhide").addClass("hidesearch");
} else {
$(".thiswillhide").removeClass("hidesearch");
}
});
</script>
thanks
answered Nov 15, 2018 at 17:58
IlnarII 2 / 2 / 0 Регистрация: 21.04.2019 Сообщений: 107 |
||||||||
1 |
||||||||
18.03.2021, 00:06. Показов 3802. Ответов 3 Метки нет (Все метки)
Как изменять цвет при прокрутке header?
__________________
0 |
120 / 95 / 15 Регистрация: 02.02.2014 Сообщений: 341 |
|
18.03.2021, 01:25 |
2 |
ну добавляйте/убирайте класс с цветом
0 |
IlnarII 2 / 2 / 0 Регистрация: 21.04.2019 Сообщений: 107 |
||||||||
18.03.2021, 20:07 [ТС] |
3 |
|||||||
Как сделать чтобы при прокрутке страницы,цвет становился черным ,а когда оно на самом вверху ,оно плавно анимировалась в прозрачный цвет
0 |
evil_pixi 120 / 95 / 15 Регистрация: 02.02.2014 Сообщений: 341 |
||||||||
19.03.2021, 06:06 |
4 |
|||||||
jsFiddle
0 |
В предыдущей статье инструкция как сделать липкий хедер.
В этой статье вы узнаете, как сделать липкий хедер, который меняет цвет или прозрачность при прокручивании.
Вы можете использовать любой пейдж-билдер или конструктор на основе Гутенберг, в котором есть весь функционал из этой статьи.
Я буду использовать Elementor Pro.
1. Создайте HERO секцию
Добавьте первую секцию, в которой находится изображение, ваше уникальное предложение, призыв к действию и так далее.
2. Создайте еще одну секцию для хедера
Добавьте еще одну секцию выше HERO секции или создайте отдельный шаблон для хедера. В этой секции будет находиться липкий прозрачный хедер.
Установите значение ширины макета, или дайте этой секции полную ширину.
а. Создайте хедер внутри этой секции
Назначьте класс stickyheadersection
этой секции. Если нужно, добавьте отступы.
б. Включите прилипание
Добавьте прилипание в настройках. Эта функция находится в Elementor Pro. Если у вас нет Pro, вы можете использовать бесплатный плагин Jet Sticky.
в. Добавьте z-index
Дайте секции z-index 999
и добавьте отрицательный отступ, чтобы поместить секцию выше первой секции.
Вместо значения -60
добавьте свое значение, которое равно высоте хедера.
г. Добавьте Смещение эффектов
Подберите нужное значение для Смещения эффектов. Это значение определяет, через сколько пикселей секция изменит цвет, который вы укажете в коде из следующего абзаца.
Добавьте CSS
Добавьте этот CSS снипет на страницу, где вы хотите иметь липкий хедер, или в сам шаблон хедера. Это можно сделать с помощью виджета HTML-код.
Если будете делать с помощью виджета HTML-код, не забудьте поставить теги <style></style>
.
Замените цвет фона хедера на свой в строке 6
. Когда вы будете прокручивать страницу вниз, хедер будет менять цвет на этот.
Вы можете использовать этот способ не только в Элементоре, но и в любом другом пейдж-билдере.
Все готово, можно проверить.
Читайте также:
- Липкое меню WordPress с помощью Elementor
- Как добавить текст на картинке при наведении мышкой
Надеюсь, статья была полезна. Оставляйте комментарии.