0

我一直在查看 IntersectionObserver 来检测 en 元素何时对用户可见,方法是检查它是否在视口内。但是,如果另一个元素覆盖了“目标”元素,似乎只有在我们知道要具体观察哪些元素的情况下才能检测到这一点,因为观察者总是需要一个目标和一个根来进行比较:

function createObserver() {
  var options = {
    root: document.querySelector('#container'),
    threshold: 0
  };

  var observer = new IntersectionObserver(callback, options);
  observer.observe(document.querySelector('#box'));
}

我需要做的是指定一个要观察的目标,然后检测任何其他元素何时覆盖它,这似乎使用 IntersectionObserver 是不可能的。感谢任何能提供帮助的人!

4

1 回答 1

2

没有直接的 JS 方法可以做到这一点。

我创建了一个自定义观察者,它也检查突变。检查代码:

// AllIntersectionObserver
function AllIntersectionObserver(callback, options) {
    this.options = options;
    this.observer = new IntersectionObserver(callback, this.options);
    this.observe(this.options.root);
    var mutationObserver = new MutationObserver(this.mutationCheck.bind(this));
    mutationObserver.observe(this.options.root, {
        childList: true,
        subtree: true
    });
}
AllIntersectionObserver.prototype.observe = function(el) {
    if (el.nodeType == 1) {
        this.observer.observe(el);
        for (var i = 0; i < el.childNodes.length; i++) {
            this.observe(el.childNodes[i]);
        }
    }
};
AllIntersectionObserver.prototype.mutationCheck = function(events) {
    for (var i = 0; i < events.length; i++) {
        var event = events[i];
        for (var ii = 0; ii < event.addedNodes.length; ii++) {
            this.observe(event.addedNodes[ii]);
        }
    }
};
// end AllIntersectionObserver

new AllIntersectionObserver(console.log, { root: document.querySelector("#c") });

document.querySelector("#add").addEventListener("click", function() {
    var sq = document.createElement("div");
    sq.className = "sq";
    document.querySelector("#c").appendChild(sq);
});

// Dragger
var dragging = null;
window.addEventListener("mousedown", function(event) {
	if (event.target.className == "sq") {
        dragging = {
            el: event.target,
            l: event.target.offsetLeft,
            t: event.target.offsetTop,
            ev: event
        };
        event.preventDefault();
    }
});
window.addEventListener("mousemove", function(event) {
	if (dragging) {
  	  dragging.el.style.left = (dragging.l + (event.pageX - dragging.ev.pageX)) + "px";
      dragging.el.style.top = (dragging.t + (event.pageY - dragging.ev.pageY)) + "px";
      event.preventDefault();
    }
});
window.addEventListener("mouseup", function(event) {
	dragging = null;
});
// Dragger
.c {
    position: relative;
    background-color: red;
    width: 100px;
    height: 100px;
}
.sq {
    position: absolute;
    left: 0;
    top: 0;
    background-color: blue;
    width: 10px;
    height: 10px;
}
<button id="add">Add square</button>
<div class="c" id="c">
    <div class="sq"></div>
</div>
Drag blue squares with mouse

于 2018-07-26T10:50:20.293 回答