import { setActiveLink, onScroll } from './utils';
import { inBrowser, randomId } from '../../shared/utils';
const cssChange = (
mysidebar: HTMLElement,
postion: string,
top: number,
left: number
) => {
mysidebar.style.position = postion;
mysidebar.style.top = top + 'px';
mysidebar.style.left = left + 'px';
};
const addEvent = (function () {
if (inBrowser && 'addEventListener' in window) {
return function (elm: Element, type: string, handle: EventListenerOrEventListenerObject) {
elm.addEventListener(type, handle, false);
};
}
})();
export default {
name: 'DAnchorBox',
mounted(el: HTMLElement): void {
const timeId = 'm' + randomId(8);
el.id = timeId;
const classList = el.classList;
classList.add('mycontainer', 'mymain', timeId);
let windoScrollTop;
const div = document.querySelector(`#${timeId}`) as HTMLElement;
const mysidebar = document.querySelector(
`#${timeId} .mysidebar`
) as HTMLElement;
const mysidebarHeight = mysidebar.clientHeight;
window.addEventListener('resize', () => {
cssChange(mysidebar, 'absolute', 0, 0);
});
window.onscroll = function () {
windoScrollTop = document.documentElement.scrollTop || document.body.scrollTop;
if (!document.getElementsByClassName('scrollTarget').length) {
if (windoScrollTop + mysidebarHeight - 16 >= div.offsetTop + div.clientHeight) {
cssChange(
mysidebar,
'absolute',
div.clientHeight - mysidebarHeight - 8,
0
);
} else if (windoScrollTop > div.offsetTop) {
cssChange(
mysidebar,
'fixed',
div.offsetTop,
div.getBoundingClientRect().left
);
} else if (div.offsetTop >= windoScrollTop && windoScrollTop >= 0) {
cssChange(mysidebar, 'absolute', 0, 0);
} else {
cssChange(mysidebar, 'absolute', div.clientHeight - mysidebarHeight - 8, 0);
}
} else {
cssChange(mysidebar, 'absolute', div.scrollTop, 0);
}
};
addEvent?.(div, 'scroll', function () {
if (document.getElementsByClassName('scrollTarget').length) {
cssChange(
mysidebar,
'fixed',
div.getBoundingClientRect().top,
div.getBoundingClientRect().left
);
}
});
setActiveLink(timeId);
document.getElementsByClassName('scrollTarget').length
? addEvent?.(div, 'scroll', onScroll)
: window.addEventListener('scroll', onScroll);
},
};