JSFiddle - React, Tailwind, and code Playground
by yshrkn
HTML
<div class="header">This is headerThis is headerThis is headerThis is headerThis is headerThis is headerThis is headerThis is headerThis is headerThis is header</div>
<div class="main">
Main area
<div class="mark"></div>
</div>
<div class="state">現在のスクロール量:<span class="scrollState"></span>px</div>
SCSS
html { height: 100%; }
body {
display: flex;
margin: 0;
height: 1000px;
flex-direction: column;
}
.header {
background: yellow;
width: 100%;
z-index: 2;
}
.main {
background: skyblue;
width: 100%;
flex-grow: 1;
z-index: 1;
position: relative;
background: linear-gradient(180deg, rgb(255, 176, 176), rgb(255, 85, 85));
}
.mark {
}
.state {
position: fixed;
right: 0;
top: 0;
background: #000;
opacity: .8;
color: #fff;
z-index: 3;
}
JavaScript
const $window = $(window);
const $header = $('.header');
const $main = $('.main');
const $body = $('body');
const $state = $('.scrollState');
$window.on('scroll resize', function () {
const headerHeight = $header.height();
const scrollValY = $window.scrollTop();
$state.text(Math.round(scrollValY));
if (scrollValY < headerHeight) {
console.log('header固定解除');
$header.css('position', 'relative');
$header.css('top', '0');
$main.css('transform', 'translateY(0)');
return;
}
console.log('header固定開始');
$header.css('position', 'fixed');
$header.css('top', 0);
$main.css('transform', `translateY(${headerHeight}px)`);
});
// 目盛り用
let txt = '';
for (i = 0; i < 200; i++) {
txt += i + '<br>';
}
$('.mark').html(txt);