【问题标题】:Javascript: move a DIV and detect when it's fully inside another DIV?Javascript:移动一个 DIV 并检测它何时完全在另一个 DIV 内?
【发布时间】:2021-04-28 17:18:25
【问题描述】:

我必须创建一个 UI,用户可以在其中单击按钮以通过单击 4 个按钮以预设增量移动 DIV(灰色框)。此外,我需要检测他们何时将其完全“移入”另一个 DIV(红色虚线)。

移动 div 似乎很简单,但我对检测灰色框是否完全在虚线框内的最佳方法感到困惑。

我可以做这个广告 HTML 或 SVG,但我的所有研究都显示了相互矛盾的结果,虽然检测交叉点看起来很简单,但我没有发现检测完全包含在不同矩形的边界中。

对方法的建议表示赞赏。

【问题讨论】:

  • 如果给你一道数学题,给出矩形的坐标和大小,并且你有铅笔和纸,你会怎么做?
  • 我假设你有左上角坐标和宽度/高度?很简单:gray.x > red.x && gray.x + gray.w < red.x && red.w y & h 相同。

标签: javascript html css svg


【解决方案1】:

您需要使用Intersection Observer API

const options = {
  root: document.querySelector('CONTAINER SELECTOR'),
  rootMargin: '0px',
  threshold: 1.0
}

const targetToWatch = document.querySelector('INSIDE ITEM SELECTOR');

let callback = (entries, observer) => {
  entries.forEach(entry => {
    // Each entry describes an intersection change for one observed
    // target element:
    //   entry.boundingClientRect
    //   entry.intersectionRatio
    //   entry.intersectionRect
    //   entry.isIntersecting
    //   entry.rootBounds
    //   entry.target
    //   entry.time
  });
};

const observer = new IntersectionObserver(callback, options);
observer.observe(targetToWatch);

然后您需要检查各种entry. 参数以了解元素是否在里面。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-15
    • 2016-02-04
    相关资源
    最近更新 更多