JavaScript检测与任何其他未知元素的交集/碰撞

时间:2018-07-26 09:48:56

标签: javascript dom collision-detection intersection-observer

我一直在查看IntersectionObserver,以通过检查元素是否在视口内来检测用户何时可见。但是,如果另一个元素覆盖了“ target”元素,则似乎只有在我们知道要具体监视哪些元素的情况下,我们才能检测到该元素,因为观察者始终会选择一个目标和一个与之进行比较的根:

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

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

我需要做的是指定一个要监视的目标,然后检测何时有其他元素覆盖该目标,这似乎无法使用IntersectionObserver来实现。感谢任何可以提供帮助的人!

1 个答案:

答案 0 :(得分:0)

没有直接的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