Created
November 22, 2019 07:20
-
-
Save caiguanhao/8942a6832b657a0c8ebc15bf7e15da99 to your computer and use it in GitHub Desktop.
simple solution to add sticky header for bootstrap 4 tables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let style = document.createElement('style') | |
document.head.appendChild(style) | |
document.addEventListener('scroll', () => { | |
let table = document.querySelector('.table') | |
if (!table) return | |
let navbar = document.querySelector('.navbar') | |
if (!navbar) return | |
let offset = table.getBoundingClientRect().top + window.scrollY - navbar.offsetHeight | |
let second = document.querySelector('.table > thead > tr:nth-child(2) > th') | |
let secondOffset = 0 | |
if (second) { | |
let first = document.querySelector('.table > thead > tr:nth-child(1) > th') | |
secondOffset = second.getBoundingClientRect().top - first.getBoundingClientRect().top | |
} | |
if (window.scrollY <= offset) { | |
style.innerHTML = '' | |
} else { | |
style.innerHTML = `.table > thead > tr > th { background: #fff; transition: top 0.2s; position: sticky; } | |
.table > thead > tr:first-child > th { top: ${window.scrollY - offset}px; } | |
.table > thead > tr:nth-child(2) > th { top: ${window.scrollY - offset + secondOffset}px; } | |
.table > thead > tr > th:before { content: ''; position: absolute; top: -2px; left: 0; right: 0; height: 2px; background: #fff; } | |
.table > thead > tr > th:after { content: ''; position: absolute; bottom: 0; left: 0; right: 0; height: 2px; background: #dee2e6; }` | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
iPhone Safari:
Mac Chrome: