效果图
/** 横向滚动条 吸附 页面底部 */
export class StickyHorizontalScrollBar {
constructor(options = {}) {
const { el, style = '' } = options
this.createScrollbar(style)
this.insertScrollbar(el)
this.setScrollbarSize()
this.onEvent()
}
/** 创建滚轴组件元素 */
createScrollbar = (style = '') => {
if (this.scrollbar) return this.scrollbar
const 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}
}
</style>
<div id="${this.thumbId}" style="height: 1px;"></div>
`
}
/** 把滚轴组件元素插入目标元素的后面 */
insertScrollbar = (el) => {
this.target = el
if (typeof el === 'string') {
this.target = document.querySelector(el)
}
if (!this.target) throw Error('el Dom do not exit')
this.targetParentElement = document.querySelector(el).parentElement
if (!this.targetParentElement.querySelector(`#${this.scrollbarId}`)) {
this.targetParentElement.insertBefore(
this.scrollbar,
this.target.nextSibling
)
}
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 stickyHorizontalScrollBar = new StickyHorizontalScrollBar({
el: '#container',
})
//重新设置滚动条尺寸
stickyHorizontalScrollBar.setScrollbarSize()
//清除事件监听器
stickyHorizontalScrollBar.removeEvent()