我有此代码:
function fetchImage(url) { /*return new Promise((resolve, reject) => {
const image = new Image();
image.src = url;
image.onload = resolve;
image.onerror = reject; });*/ return new Promise(function(resolve, reject){ const image = new Image(); image.src = url; image.onload = resolve; image.onerror = reject; }); }
function applySrc(el, src){ el.classList.add('loaded'); el.src = `${src}`; }
function applyBg(el, src){ el.classList.add('loaded'); el.style.backgroundImage = `url('${src}')`; }
const options3 = { rootMargin: '200px', threshold: 0.1 }
const callback_src = function(entries){ entries.forEach(function(entry){
const ratio = entry.intersectionRatio;
const element = entry.target;
if(ratio > 0){
observer.unobserve(element);
const src = element.dataset.src
fetchImage(src).then(function(){
applySrc(element, src);
});
} }); }
const callback_bg = function(entries){ entries.forEach(function(entry){
const ratio = entry.intersectionRatio;
const element = entry.target;
if(ratio > 0){
observer.unobserve(element);
const src = element.dataset.src
fetchImage(src).then(function(){
applyBg(element, src);
});
} }); }
const observer = new IntersectionObserver(callback_src, options3);
const observer2 = new IntersectionObserver(callback_bg, options3);
const targets = document.querySelectorAll('.intersection-observer-img');
const targets2 = document.querySelectorAll('.intersection-observer-bg');
targets.forEach(function(target){observer.observe(target)});
targets2.forEach(function(target){ observer2.observe(target)});
在Chrome,Safari 12,Firefox等上可以,但是在IE和Safari 9.0上不起作用。 问题似乎是 targets.forEach(function(target){observer.observe(target)}); ,因为错误是“ targets.forEach不是函数”。