仅在拖动项目时禁用指针事件

Disable pointer-events only when dragging over an item

我有一个容器,其中包含用户可以与之交互的动态内容。它可以是 YouTube 视频 (iframe) 等。

用户可以将图像拖放到此容器中,它会用他们的图像替换动态内容。

我知道由于内容是动态的,拖动事件在容器中的行为会不稳定,所以我需要做 pointer-events: none

HTML 容器有以下 classes ant-upload-dragant-upload-drag-hoverant-upload-drag-hover class 仅当被拖动的图像位于容器顶部时才处于活动状态。

我有 CSS 类似于以下内容,其中 ant-upload-drag-container 包含我希望指针事件无法访问的动态内容:

.ant-upload-drag-hover {
  .ant-upload-drag-container {
    pointer-events: none;
  }
}

不幸的是,这不起作用。它导致容器行为不稳定,ant-upload-drag-hover class 一遍又一遍地添加和删除容器。

同时,以下工作:

.ant-upload-drag {
  .ant-upload-drag-container {
    pointer-events: none;
  }
}

基本上,只要 .ant-upload-drag-container 始终是 pointer-events: none;,事情就会按预期进行,但是如果 pointer-events: none 在悬停时动态触发,那么事情就不会按计划进行。

以下视频直观演示:

https://share.getcloudapp.com/ApuRgQlZ

第一个示例显示了所需内容(当指针事件始终为 none 时)。第二个示例显示当前状态(当指针事件动态转移到始终 none)时。

我知道这没什么大不了的,但我不确定我是否从根本上误解了 pointer-events: none,或者是否正在发生一些 React 渲染恶作剧。

据推测,将 ant-upload-drag-hover class 添加到元素的那一刻, pointer-events: none 会触发,但似乎由于某种原因 pointer-events: none 也被触发容器或其他东西必须发生,容器才能失去悬停状态并删除 class.

我不确定 pointer-events: none 是否会干扰拖放事件,但它可以解释您的错误。

我建议您改为在容器顶部放置一个层来捕获这些事件。

这是一个带有按钮的示例,图层每 3 秒切换一次(class)。

// toggle class `ant-upload-drag-hover` every 3 seconds
setInterval(() => {
  document.querySelector(".ant-upload-drag").classList.toggle("ant-upload-drag-hover");
}, 3000);
.ant-upload-drag-container {
  position: relative;
}

.ant-upload-drag-hover .ant-upload-drag-container::before {
  content: "";
  display: block;
  position: absolute;
  z-index: 999;
  height: 100%;
  width: 100%;
  /* the rest is just for aesthetics: */
  content: " .ant-upload-drag-hover";
  background: rgba(255, 255, 255, .5);
  cursor: not-allowed;
}

button {
  padding: 50px 100px;
}

button::before {
  content: "Click here: ";
}
<div class="ant-upload-drag">
  <div class="ant-upload-drag-container">
    <button onclick="++this.textContent">0</button>
  </div>
</div>