【问题标题】:Click outside of Div to close it. SVG & D3, Angular单击 Div 外部将其关闭。 SVG 和 D3,角度
【发布时间】:2019-02-17 02:42:46
【问题描述】:

我想点击 div 之外的任何地方来隐藏它。

我有一个 svg 背景,上面有一个带节点的图表。

我点击我的 SVG 上的一个节点(圆圈),如果点击了这个特定的“额外”节点,那么我会出现一个框,我会显示该框:

  d3.select('#rightBox')
  .attr('hidden', null);
d3.select('#leftBox')
  .attr('hidden', null);
d3.select('#headerDiv')
  .attr('hidden', null)
d3.select('#headerText')
  .attr('hidden', null)

这是因为 div 在加载时是隐藏的。我没有使用 css 显示属性,因为它不起作用!

问题是当我在主体上尝试 angular (click) = "functionThatHidesTheDiv" 并隐藏元素时,当然因为圆形节点是主体的一部分,那么盒子永远不会打开?

我也使用角度。一旦元素没有被隐藏,我如何点击 svg 上的任何地方,不包括 div 本身来隐藏它?

【问题讨论】:

    标签: javascript angular d3.js svg


    【解决方案1】:

    您需要检查点击事件的“目标”是 div,还是在其中。

    也许是这样的?

    const svg = document.querySelector('.svg');
    const circle = document.querySelector('.circle');
    
    svg.addEventListener('click', (e) => {
     if (!(e.target === circle) && !circle.contains(e.target)) {
       console.log('Click outside');
     } else {
      console.log('Click inside');
     }
    });
    .svg {
      display: flex;
      justify-content:center;
      align-items: center;
      width: 400px;
      height: 400px;
      background-color: tomato;
    }
    
    .circle {
      width: 50px;
      height: 50px;
      border-radius: 50%;
      background-color: tan;
    }
    <section>
      <div class="svg">
        <div class="circle"></div>
      </div>
    </section>

    【讨论】:

    • 我认为 document.queryselector 不适用于我的 Angular 应用程序,但这看起来确实很接近......这可以与 D3 一起使用吗?
    • 是的,document.querySelector 用于 vanilla.js,如果你想对 angular 做同样的事情,你可能需要使用 @ViewChild 来获取对你不想要的元素的引用排除
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-24
    • 2011-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多