<div class="box box1"></div>

<div class="box box2"></div>

<div class="box box3"></div>
.box1 {
  margin: 25px auto;
  width: 200px;
  height: 200px;
  background-color: red;
  text-align: center;
  line-height: 200px;
  color: #fff;
  font-size: 24px;
}

.box2 {
  margin: 25px auto;
  width: 200px;
  height: 100px;
  background-color: red;
  text-align: center;
  line-height: 100px;
  color: #fff;
  font-size: 24px;
}

.box3 {
  margin: 25px auto;
  width: 100px;
  height: 200px;
  background-color: red;
  text-align: center;
  line-height: 200px;
  color: #fff;
  font-size: 24px;
}
$(function () {
  var oBox = $(".box");

  $(oBox).on("mouseenter", function (e) {
    this.innerText = getDirection(e, this);
  });

  var getDirection = function (e, elem) {
    var e = e || window.event;
    var $elem = $(elem),
      boxWidth = $elem.width(),
      boxHeight = $elem.height(),
      offsetLeft = $elem.offset().left,
      offsetTop = $elem.offset().top,
      x =
        (e.clientX - offsetLeft - boxWidth / 2) *
        (boxWidth > boxHeight ? boxHeight / boxWidth : 1),
      y =
        (e.clientY - offsetTop - boxHeight / 2) *
        (boxHeight > boxWidth ? boxWidth / boxHeight : 1);

    var radius = (Math.atan2(y, x) * 180) / Math.PI + 180;

    /*
      top -135 ~ -45
      right -135 ~ 45
      bottom 45 ~ 135
      left -180 ~ -135, 135 ~ 180
    */

    // 加 180 是为了不出现负数

    /*                                        +3     %4
      top 45 ~ 135                1            4      0
      right 45 ~ 225              2            5      1    
      bottom 225 ~ 315            3            6      2
      left 0 ~ 45, 315 ~ 360      0, 4      3, 4      3
    */

    var direction = (Math.round(radius / 90) + 3) % 4;

    switch (direction) {
      case 0:
        return "top";
      case 1:
        return "right";
      case 2:
        return "bottom";
      case 3:
        return "left";
      default:
        return "";
    }
  };
});

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

  1. https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js