首页 > 解决方案 > 根据单击的鼠标位置定位 div

问题描述

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

标签: javascriptcssangular

解决方案


在您的 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;
  }
}

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


推荐阅读