-
-
Notifications
You must be signed in to change notification settings - Fork 232
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
图片懒加载 #68
Comments
const images = document.querySelectorAll("image");
const observer = new IntersectionObserver((entries, observer) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
entry.target.src = entry.target.dataset.src;
observer.unobserve(entry.target);
}
});
});
images.forEach((image) => {
observer.observe(image);
}); |
补充:react可以直接用组件 |
const images = document.querySelectorAll("img")
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
// 判断当前元素是否可见
if (entry.isIntersecting) {
// 创建一个自定义属性data-src存放真正要显示的图片路径,原本img自带的src放一张默认图片
const img = entry.target
const data_src = img.getAttribute('data-src')
img.setAttribute('src', data_src)
// 解除观察,有几张图片就触发几次
observer.unobserve(img)
}
})
})
images.forEach(image => {
// 对每一个图片对象进行观察
observer.observe(image)
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No description provided.
The text was updated successfully, but these errors were encountered: