카카오공식홈페이지에 보면 스크롤 시 오른쪽 콘텐츠는 고정되고 왼쪽 콘텐츠들을 스크롤이 된다.
css와 jquery를 사용한 codepen을 찾아 정리해보았다.
<header></header>
<div class="container">
<section class="one">
<div class="left">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
<div class="right">
<div class="right-child">
<h2>Scroll</h2>
</div>
</div>
</section>
<div class="next_content"></div>
</div>
* { margin: 0; box-sizing: border-box; }
header { width: 100%; height: 100px; background: #2e446d; }
.container { width: 992px; height: 100%; margin: 0 auto; padding: 25px; background: #b3c1da; }
section.one { position: relative; }
section.one::after { display: block; content: ''; clear: both; }
.left { float: left; width: calc(50% - 12px); margin-right: 25px; }
.left > div { width: 100%; height: 200px; background: #ccd9f1; margin-bottom: 25px; }
.right { float: right; width: calc(50% - 13px); }
.right-child { width: 428px; padding: 10px; background: #8da8d0; text-align: center; color: #fff; }
.right-child.posFix { position: fixed; top: 25px; }
.right-child.posAbs { position: absolute; bottom: 25px; }
.next_content { width: 100%; height: 900px; background: #8698b9; }
@media (max-width: 992px) {
.container { width: 100%; }
.left { width: 100%; }
.right { width: 100%; }
.right .right-child { width: 100%; }
}
$(document).ready(function() {
$(window).off()on('resize scroll', reOrder);
function reOrder() {
var mq = window.matchMedia('(min-width: 993px)');
if(mq.matches) {
// 992px 이상 스크립트 적용.
$('.right-child').addClass('customm');
$('.right-child h2').text('scroll');
var scroll = $(window).scrollTop();
var topCnt = $('.one').position().top - 25;
var leftH = $('.left').height();
var rightH = $('.right-child').height();
// 'header높이' + 'one높이' - 'right-child높이'
var bottomCnt = topCnt + leftH - (rightH * 2);
if(scroll > topCnt && scroll < bottomCnt) {
// console.log('scroll이 one 부분');
$('.customm').removeClass('posAbs').addClass('posFix');
} else if (scroll > bottomCnt) {
// console.log('scroll이 next_content 부분');
$('.customm').removeClass('posFix').addClass('posAbs');
} else if (scroll < topCnt) {
// console.log('scroll이 header 부분');
$('.customm').removeClass('posFix');
}
} else {
// 992px 미만 스크립트 적용.
$('.right-child').removeClass('customm posAbs posFix');
$('.right-child h2').text('Fixed');
}
}
})
javascript - window.matchMedia()
- IE 10 부터 지원.
- 지정된 CSS 미디어쿼리 문자열의 결과를 나타내느 mediaQueryList 객체 반환.
- 값은
min-height
,min-width
,orientation
등과 같은 CSS @media 규칙 미디어 기능 중 하나. - MediaQueryLsit 객체는 두 개의 속성과 두 개의 메서드를 가진다.
[속성]
matches
:: 쿼리 결과 참거짓 확인.
media
:: mediaQueryString 반환.
var jbMedia = window.matchMedia('(min-width: 500px)');
document.write('<p>' + jbMedia.media + ' / ' + jbMedia.matches + '</p>')
// all and (min-width: 500px) / true
Reference
https://codepen.io/icorrea/pen/eBPdOR