所以,我有一個固定的元素(#logo-icon),我需要添加一個類(。inverted)每當背景圖像被加載到任何其他div中時,當用戶滾動時,該div可能碰巧出現在它的下面。我似乎找不到任何工作。提前感謝。下面是一些代碼:
// Select the target element
var logoIcon = document.querySelector('#logo-icon');
// Create a new Intersection Observer instance
var observer = new IntersectionObserver(function(entries) {
entries.forEach(function(entry) {
// Check if the target element is intersecting with any other element
if (entry.isIntersecting) {
// Check if the intersecting element or its children have a background image
var intersectingElement = entry.target;
var hasBackgroundImage = checkBackgroundImage(intersectingElement);
if (hasBackgroundImage) {
// Add the "inverted" class to the logoIcon element
logoIcon.classList.add('inverted');
} else {
// Remove the "inverted" class from the logoIcon element
logoIcon.classList.remove('inverted');
}
}
});
}, { threshold: 0.5 });
// Start observing the logoIcon element
observer.observe(logoIcon);
// Function to check if an element or its children have a background image
function checkBackgroundImage(element) {
// Check if the element itself has a background image
var computedStyle = window.getComputedStyle(element);
if (computedStyle.getPropertyValue('background-image') !== 'none') {
return true;
}
// Check if any child element has a background image
var childElements = element.children;
for (var i = 0; i < childElements.length; i++) {
var childComputedStyle = window.getComputedStyle(childElements[i]);
if (childComputedStyle.getPropertyValue('background-image') !== 'none') {
return true;
}
}
return false;
}
`