Skip to content
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

Open
Sunny-117 opened this issue Nov 3, 2022 · 3 comments
Open

图片懒加载 #68

Sunny-117 opened this issue Nov 3, 2022 · 3 comments

Comments

@Sunny-117
Copy link
Owner

No description provided.

@bearki99
Copy link

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);
});

@bearki99
Copy link

补充:react可以直接用组件

@vuemenow
Copy link

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
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants