[Add] navbar scrollspy directive

Add navbar scrollspy
navbar style improvement
This commit is contained in:
Tony Yang
2021-01-27 22:53:58 +08:00
parent 5141a28a50
commit dd3708d493
4 changed files with 63 additions and 3 deletions

View File

@@ -0,0 +1,37 @@
import Vue, { DirectiveOptions, VNode, VNodeDirective } from 'vue';
let selectors!: string[];
let observer!: IntersectionObserver;
const ScrollSpyDirective: DirectiveOptions = {
bind (el: Element, binding: VNodeDirective , vnode: VNode) {
selectors = binding.value.selectors;
// highlight first element
el.querySelector(`[href="${location.hash || selectors[0] || ''}"]`)?.classList.toggle('active', true);
const config = {
rootMargin: '-10% 0px -80% 0px',
threshold: 0
};
observer = new IntersectionObserver((entries, observer) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
selectors.forEach((selector: string) => {
el.querySelector(`[href="${selector}"`)?.classList.toggle('active', selector === `#${entry.target.id}`);
});
}
});
}, config);
selectors.forEach((selector: string) => {
observer.observe(document.querySelector(selector) as Element);
});
},
unbind () {
observer.disconnect();
}
};
export default ScrollSpyDirective;