const lazyLoad = {
// install方法
install (Vue, options) {
const defaultSrc = options.default
Vue.directive('lazy', {
bind (el, binding) {
lazyLoad.init(el, binding.value, defaultSrc)
},
inserted (el) {
if (IntersectionObserver) {
lazyLoad.observe(el)
} else {
lazyLoad.listenerScroll(el)
}
}
})
},
// 初始化
init (el, val, def) {
el.setAttribute('data-src', val)
el.setAttribute('src', def)
},
// 利用IntersectionObserver监听el
observe (el) {
var io = new IntersectionObserver((entries) => {
const realSrc = el.dataset.src
if (entries[0].isIntersecting) {
if (realSrc) {
el.src = realSrc
el.removeAttribute('data-src')
}
}
})
io.observe(el)
},
// 监听scroll事件
listenerScroll (el) {
const handler = lazyLoad.throttle(lazyLoad.load, 300)
lazyLoad.load(el)
window.addEventListener('scroll', () => {
handler(el)
})
},
// 加载真实图片
load (el) {
const windowHeight = document.documentElement.clientHeight
const elTop = el.getBoundingClientRect().top
const elBtm = el.getBoundingClientRect().bottom
const realSrc = el.dataset.src
if (elTop - windowHeight < 0 && elBtm > 0) {
if (realSrc) {
el.src = realSrc
el.removeAttribute('data-src')
}
}
},
// 节流
throttle (fn, delay) {
let timer
let prevTime
return function (...args) {
const currTime = Date.now()
const context = this
if (!prevTime) prevTime = currTime
clearTimeout(timer)
if (currTime - prevTime > delay) {
prevTime = currTime
fn.apply(context, args)
clearTimeout(timer)
return
}
timer = setTimeout(function () {
prevTime = Date.now()
timer = null
fn.apply(context, args)
}, delay)
}
}
}
export default lazyLoad
没有合适的资源?快使用搜索试试~ 我知道了~
directive-vue2.zip
资源详情
资源评论
资源推荐
收起资源包目录
directive-vue2.zip (9个子文件)
directive-vue2
index.js 630B
commom
longpress.js 1KB
debounce.js 291B
copy.js 1KB
draggable.js 937B
emoji.js 846B
waterMarker.js 827B
lazyLoad.js 2KB
permission.js 587B
共 9 条
- 1
九号窗口
- 粉丝: 196
- 资源: 12
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功
评论0