lovelylw-reach-bottom
Version:
滑到底部加载更多的功能
82 lines (77 loc) • 2.62 kB
JavaScript
export default{
install(Vue) {
// 上滑加载的全局指令
Vue.directive('reach-bottom', {
bind (el, binding, vnode, oldVnode) {
let scrollReduce = binding.arg || 300
let windowHeight = window.screen.height
let height
let setTop
let paddingBottom
let marginBottom
// let requestFram
let scrollEl
let heightEl
let scrollType = el.attributes.type && el.attributes.type.value
let touchmoveFlag = false
// console.log('scrollType', scrollType)
// let scrollReduce = 20
let pageYS = 0
let pageYE = 0
if (scrollType == 2) {
scrollEl = el
heightEl = el.children[0]
} else {
scrollEl = document.body
heightEl = el
}
el.addEventListener('touchstart', e => {
pageYS = e.touches[0].pageY
// oldScrollTop = scrollEl.scrollTop
height = heightEl.clientHeight
// if (scrollType == 2) {
// height = height
// }
setTop = el.offsetTop
paddingBottom = getStyle(el, 'paddingBottom')
marginBottom = getStyle(el, 'marginBottom')
}, false)
el.addEventListener('touchmove', e => {
pageYE = e.touches[0].pageY
if (Math.abs(pageYE - pageYS) > 2) {
touchmoveFlag = true
}
}, false)
el.addEventListener('touchend', e => {
// if (Math.abs(pageYE - pageYS) > 2) {
if (touchmoveFlag) {
height = heightEl.clientHeight
touchmoveFlag = false
loadMore()
}
}, false)
/**
* 获取style样式
*/
let getStyle = (element, attr, NumberMode = 'int') => {
let target
// scrollTop 获取方式不同,没有它不属于style,而且只有document.body才能用
if (attr === 'scrollTop') {
target = element.scrollTop
} else if (element.currentStyle) {
target = element.currentStyle[attr]
} else {
target = document.defaultView.getComputedStyle(element, null)[attr]
}
// 在获取 opactiy 时需要获取小数 parseFloat
return NumberMode == 'float' ? parseFloat(target) : parseInt(target)
}
const loadMore = () => {
if ((scrollEl.scrollTop || window.pageYOffset) + windowHeight >= height + setTop + paddingBottom + marginBottom - scrollReduce) {
binding.value()
}
}
}
})
}
}