image lazy load

This commit is contained in:
xiaomlove
2022-08-31 23:08:26 +08:00
parent 8d3d404141
commit 138ee2b86a
7 changed files with 100 additions and 7 deletions

37
public/js/nexus.js vendored
View File

@@ -8,9 +8,21 @@ jQuery(document).ready(function () {
}
})
// preview
function getPosition(e, imgEle) {
let imgWidth = imgEle.prop('naturalWidth')
let imgHeight = imgEle.prop("naturalHeight")
console.log(`imgWidth: ${imgWidth}, imgHeight: ${imgHeight}`)
let ratio = imgWidth / imgHeight;
if (imgWidth > window.innerWidth) {
imgWidth = window.innerWidth;
imgHeight = imgWidth / ratio;
}
if (imgHeight > window.innerHeight) {
imgHeight = window.innerHeight;
imgWidth = imgHeight * ratio;
}
let width = imgWidth, height= imgHeight;
let left = e.pageX + 10;
if (left + imgWidth > window.innerWidth) {
left = e.pageX - 10 - imgWidth
@@ -19,7 +31,9 @@ jQuery(document).ready(function () {
if (top + imgHeight > window.innerHeight) {
top = e.pageY - imgHeight / 2
}
return {left, top}
let result = {left, top, width, height}
console.log(result)
return result
}
var previewEle = jQuery('#nexus-preview')
var imgEle, selector = '.preview'
@@ -37,4 +51,25 @@ jQuery(document).ready(function () {
previewEle.css(position)
})
// lazy load
if ("IntersectionObserver" in window) {
const imgList = [...document.querySelectorAll('.nexus-lazy-load')]
var io = new IntersectionObserver((entries) =>{
entries.forEach(item => {
// isIntersecting是一个Boolean值判断目标元素当前是否可见
if (item.isIntersecting) {
item.target.src = item.target.dataset.src
item.target.classList.add('preview')
// 图片加载后即停止监听该元素
io.unobserve(item.target)
}
})
}, {
root: document.querySelector('body')
})
// observe遍历监听所有img节点
imgList.forEach(img => io.observe(img))
}
})