align.js 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. // 检测各边是否超出
  2. export function getOutSides(x, y, width, height, limitBox) {
  3. var hits = {
  4. left: x < limitBox.x,
  5. right: x + width > limitBox.x + limitBox.width,
  6. top: y < limitBox.y,
  7. bottom: y + height > limitBox.y + limitBox.height,
  8. };
  9. return hits;
  10. }
  11. export function getPointByPosition(x, y, offset, width, height, position) {
  12. var px = x;
  13. var py = y;
  14. switch (position) {
  15. case 'left': // left center
  16. px = x - width - offset;
  17. py = y - height / 2;
  18. break;
  19. case 'right':
  20. px = x + offset;
  21. py = y - height / 2;
  22. break;
  23. case 'top':
  24. px = x - width / 2;
  25. py = y - height - offset;
  26. break;
  27. case 'bottom':
  28. // bottom
  29. px = x - width / 2;
  30. py = y + offset;
  31. break;
  32. default:
  33. // auto, 在 top-right
  34. px = x + offset;
  35. py = y - height - offset;
  36. break;
  37. }
  38. return {
  39. x: px,
  40. y: py,
  41. };
  42. }
  43. export function getAlignPoint(x, y, offset, width, height, position, limitBox) {
  44. var point = getPointByPosition(x, y, offset, width, height, position);
  45. if (limitBox) {
  46. var outSides = getOutSides(point.x, point.y, width, height, limitBox);
  47. if (position === 'auto') {
  48. // 如果是 auto,默认 tooltip 在右上角,仅需要判定右侧和上测冲突即可
  49. if (outSides.right) {
  50. point.x = Math.max(0, x - width - offset);
  51. }
  52. if (outSides.top) {
  53. point.y = Math.max(0, y - height - offset);
  54. }
  55. }
  56. else if (position === 'top' || position === 'bottom') {
  57. if (outSides.left) {
  58. // 左侧躲避
  59. point.x = limitBox.x;
  60. }
  61. if (outSides.right) {
  62. // 右侧躲避
  63. point.x = limitBox.x + limitBox.width - width;
  64. }
  65. if (position === 'top' && outSides.top) {
  66. // 如果上面对齐检测上面,不检测下面
  67. point.y = y + offset;
  68. }
  69. if (position === 'bottom' && outSides.bottom) {
  70. point.y = y - height - offset;
  71. }
  72. }
  73. else {
  74. // 检测左右位置
  75. if (outSides.top) {
  76. point.y = limitBox.y;
  77. }
  78. if (outSides.bottom) {
  79. point.y = limitBox.y + limitBox.height - height;
  80. }
  81. if (position === 'left' && outSides.left) {
  82. point.x = x + offset;
  83. }
  84. if (position === 'right' && outSides.right) {
  85. point.x = x - width - offset;
  86. }
  87. }
  88. }
  89. return point;
  90. }
  91. //# sourceMappingURL=align.js.map