Going forward, the new HTML Intersection Observer API is the thing you're looking for. It allows you to configure a callback that is called whenever one element, called the target, intersects either the device viewport or a specified element. It's available in latest versions of Chrome, Firefox and Edge. See https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API for more info.
Simple code example for observing display:none switching:
// Start observing visbility of element. On change, the
// the callback is called with Boolean visibility as
// argument:
function respondToVisibility(element, callback) {
var options = {
root: document.documentElement,
};
var observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
callback(entry.intersectionRatio > 0);
});
}, options);
observer.observe(element);
}
In action: https://jsfiddle.net/elmarj/u35tez5n/5/
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…