原理分析
先将img标签的src链接设为同一张图片(默认图片),当js监听到该图片进入可视窗口时,再将实际地址应用。
实现方法
/**
* 判断元素是否在可视范围
*/
function isVisible( ele) {
let windowHeight = window.innerHeight
let position = ele.getBoundingClientRect( )
// 当元素的top偏移量小于页面大小并且大于高度的负数
if( position.top< windowHeight && position.top> -position.height) {
return true
}
return false
}
function lazyLoad ( img, src ) {
if ( img && src && isVisible ( img) ) {
setTimeout ( function ( ) {
img. setAttribute ( 'src' , src)
} , 1000 )
}
}
window. addEventListener ( 'scroll' , function ( ) {
lazyLoad ( img, src)
} )
Vue插件实现代码
function isVisible ( el ) {
let windowHeight = window. innerHeight
let position = el. getBoundingClientRect ( )
if ( position. top< windowHeight && position. top> - position. height) {
return true
}
return false
}
function lazyLoad ( img, src ) {
if ( img && src && isVisible ( img) ) {
setTimeout ( function ( ) {
img. setAttribute ( 'src' , src)
} , 1000 )
}
}
export default {
install ( Vue, options ) {
Vue. directive ( 'lazy' , {
bind : function ( el, binding, vnode ) {
el. setAttribute ( 'src' , options. loading)
window. addEventListener ( 'scroll' , function ( ) {
lazyLoad ( el, binding. value)
} )
} ,
inserted : function ( el, binding, vnode ) {
lazyLoad ( el)
}
} )
}
}
原文链接:https://www.jianshu.com/p/57e1055cc3fb