根据单击的鼠标位置来定位div

时间:2018-10-08 10:13:22

标签: javascript css angular

我需要显示一个弹出窗口,其位置与角度4中单击的鼠标坐标有关。 一个完美的例子是在Google日历中创建事件

1 个答案:

答案 0 :(得分:2)

在您的HTML中:

<div class="click-container" (click)="onMouseClick($event)"></div>

在您的TS中:

onMouseClick(e: MouseEvent) {
  console.log(e);
  //e.pageX will give you offset from left screen border
  //e.pageY will give you offset from top screen border

  //determine popup X and Y position to ensure it is not clipped by screen borders
  const popupHeight = 400, // hardcode these values
    popupWidth = 300;    // or compute them dynamically

  let popupXPosition,
      popupYPosition

  if(e.clientX + popupWidth > window.innerWidth){
      popupXPosition = e.pageX - popupWidth;
  }else{
      popupXPosition = e.pageX;
  }

  if(e.clientY + popupHeight > window.innerHeight){
      popupYPosition = e.pageY - popupHeight;
  }else{
      popupYPosition = e.pageY;
  }
}

然后,您需要使用相关代码初始化弹出组件。