mirror of
https://github.com/lkddi/nexusphp.git
synced 2026-04-14 20:40:49 +08:00
image lazy load
This commit is contained in:
37
public/js/nexus.js
vendored
37
public/js/nexus.js
vendored
@@ -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))
|
||||
}
|
||||
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user