自造轮子,不是特别好用,需要根据需求改一些代码
设置懒加载元素
export function setLazyLoad(element, callback) {
let timer;
// 火狐浏览器
document.addEventListener('DOMMouseScroll', () => {
if (!isInViewPort(element) || timer) {
return;
}
timer = setTimeout(() => {
clearTimeout(timer);
timer = null;
}, 3000);
callback();
})
// 其余浏览器
window.onmousewheel = function() {
if (!isInViewPort(element) || timer) {
return;
}
timer = setTimeout(() => {
clearTimeout(timer);
timer = null;
}, 3000);
callback();
}
}
// 元素是否在可视区域
function isInViewPort(element) {
const viewPortHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
const offsetTop = element.offsetTop
const scrollTop = document.documentElement.scrollTop
const top = offsetTop - scrollTop
return top <= viewPortHeight + 100
}
在组件里使用示范:
setLazyLoad(document.getElementById('lazy-load'), myLazyLoadFunction);
const myLazyLoadFunction = () => {
blablabla
}
销毁监听事件:
onUnmounted(() => {
document.removeEventListener('DOMMouseScroll', () => {});
window.onmousewheel = null;
})
将一个元素设置成自动隐藏滚动条的样式
// 将一个元素设置成自动隐藏滚动条的样式
export function setDynamicHiddenScrollBar({ element, timeout, paddingRight }) {
element.style.overflowY = 'hidden';
let timeoutId;
// 火狐浏览器
document.addEventListener('DOMMouseScroll', (e) => {
element.style.overflowY = 'scroll';
element.style.paddingRight = `${paddingRight - 8}px`;
element.scrollTo({
top: element.scrollTop + e.detail * 100,
behavior: 'smooth'
});
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
element.style.overflowY = 'hidden';
element.style.paddingRight = `${paddingRight}px`;
}, timeout);
})
// 其余浏览器
element.onmousewheel = function (e) {
element.style.overflowY = 'scroll';
element.style.paddingRight = `${paddingRight - 4}px`;
element.scrollTo({
top: element.scrollTop - (e.wheelDeltaY / 180) * 275,
});
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
element.style.overflowY = 'hidden';
element.style.paddingRight = `${paddingRight}px`;
}, timeout);
}
}