DEV/javascript
Javascript Html Table 헤더, 바디 스크롤 따로 컨트롤하기
석봉
2023. 11. 16. 09:48
1. Header(헤더)는 그대로 두고 Body(바디)만 따로 스크롤 이동이 필요한 경우
<!-- HTML -->
<!-- 테이블 기본 구조 -->
<!-- 헤더와 바디를 따로 div로 잡아 주어야 따로 컨트롤 가능 -->
<div>
<!-- 테이블 header -->
<div class="search-result-table-header">
<table>
<thead>
<tr></tr>
</thead>
</table>
</div>
<!-- 테이블 body -->
<div class="search-result-table-body">
<table>
<tbody></tbody>
</table>
</div>
</div>
// CSS
.search-result-table-body {
min-height: 580px; // 원하는 사이즈 고정
max-height: 580px;
overflow-y: auto; // 스크롤 생성
}
2. Body(바디)의 가로 스크롤에 따라 헤더가 같이 움직이게 할 필요가 있는 경우 (하단 이벤트를 추가)
/**
* [가로 스크롤 이벤트]
* - table body의 스크롤을 위해 header와 body가 다른 container로 구성됨.
* - table body와 table header가 다른 container이기 때문에 body에서 가로 스크롤을 이동하면 header의 가로 스크롤을 움직이지 않음.
* - body의 가로 스크롤을 움직일 때, header의 가로 스크롤의 값을 body 가로 스크롤과 맞춰줌
*/
function horizontalScrollEvent() {
const body = document.querySelector('.search-result-table-body');
const header = document.querySelector('.search-result-table-header');
body.addEventListener('scroll', (event) => {
header.scrollTo({ top: 0, left: event.target.scrollLeft });
});
}