效果图
/** 横向滚动条 吸附 页面底部 */
export class StickyHorizontalScrollBar {constructor(options = {}) {const { el, style = '' } = optionsthis.createScrollbar(style)this.insertScrollbar(el)this.setScrollbarSize()this.onEvent()}/** 创建滚轴组件元素 */createScrollbar = (style = '') => {if (this.scrollbar) return this.scrollbarconst timer = Date.now()this.thumbId = `thumb${timer}`this.scrollbarId = `scrollbar${timer}`this.scrollbar = document.createElement('div')this.scrollbar.setAttribute('id', this.scrollbarId)this.scrollbar.innerHTML = `<style>#${this.scrollbarId} {position: sticky;width: 100%;box-shadow: 0 15px 0 0 #fff;bottom: 8px;left: 0;height: 17px;overflow-x: auto;overflow-y: hidden;margin-top: -17px;z-index: 3;${style}}#${this.scrollbarId} #${this.thumbId} {height: 17px;}</style><div id="${this.thumbId}"></div>`}/** 把滚轴组件元素插入目标元素的后面 */insertScrollbar = (el) => {this.target = document.querySelector(el)if (!this.target) throw Error('el Dom do not exit')this.targetParentElement = document.querySelector(el).parentElementthis.targetIndex = [...this.targetParentElement.children].findIndex((item) => item === this.target)this.insertIndex = this.targetIndex + 1if (!this.targetParentElement.querySelector(`#${this.scrollbarId}`)) {if (this.insertIndex >= this.targetParentElement.children.length - 1) {this.targetParentElement.appendChild(this.scrollbar)} else {this.targetParentElement.insertBefore(this.scrollbar,this.targetParentElement.children[this.insertIndex])}}return this.target}/** 设置 滚轴组件元素尺寸 */setScrollbarSize = () => {this.scrollbar.style.width = this.target.clientWidth + 'px'this.scrollbar.querySelector(`#${this.thumbId}`).style.width =this.target.scrollWidth + 'px'}/** 监听目标元素和滚轴元素的scroll和页面resize事件 */onEvent = () => {this.target.addEventListener('scroll', this.onScrollTarget)this.scrollbar.addEventListener('scroll', this.onScrollScrollbar)window.addEventListener('resize', this.setScrollbarSize)}/** 移除事件 */removeEvent = () => {this.target.removeEventListener('scroll', this.onScrollTarget)this.scrollbar.removeEventListener('scroll', this.onScrollScrollbar)window.removeEventListener('resize', this.setScrollbarSize)}onScrollTarget = (e) => {this.scrollbar.scrollLeft = e.target.scrollLeft}onScrollScrollbar = (e) => {this.target.scrollLeft = e.target.scrollLeft}
}
//用法
const stickyScrollBar= new StickyScrollBar({el: '#container',
})//重新设置滚动条尺寸
stickyScrollBar.setScrollbarSize()