<p>全局提示示例:<br>
  用<b>事假委托+自定义属性</b>的方式,支持全局任意元素的鼠标提示内容显示</p>
<p>LaLaLa LaLaLa LaLaLa LaLaLa LaLaLa LaLaLa LaLaLa LaLaLa LaLaLa</p>
<button data-tooltip="the tooltip is longer than the element">Short button</button>
<button data-tooltip="HTML<br>tooltip">鼠标提示-一个长按钮</button>
<p data-tooltip="P标签<br>提示信息">Scroll the page to make buttons appear on the top, check if the tooltips show up
  correctly.</p>
<script>

</script>
body {
  height: 2000px;
}

.tooltip {
  border: 1px solid skyblue;
  border-radius: 3px;
  padding: 5px 8px;
  text-align: center;
  background-color: aliceblue;
  box-shadow: 2px 2px 3px black;
  position: fixed;
  width: max-content;
}
//思路1:查找元素,逐一添加事件 //思路2:body上添加事件委托,判断元素的自定义属性
//显示提示框:绝对定位元素,定位根据target的位置。
//事件:mouseenter、mouseleave?onmouseover、mouseout
const tip = document.createElement("div");
tip.innerHTML = "sssss";
tip.className = "tooltip";
let currentElement;
document.onmouseover = function (e) {
  let target = e.target;
  let tipHtml = e.target.dataset.tooltip;
  if (!tipHtml) return;
  currentElement = target;
  tip.innerHTML = tipHtml;
  document.body.append(tip);
  updateLocation(e);
};
document.onmouseout = function (e) {
  if (!currentElement) return;
  currentElement = null;
  tip.remove();
};

function updateLocation(e) {
  if (!currentElement || !tip) return;
  const rectTarget = currentElement.getBoundingClientRect();
  const rectTip = tip.getBoundingClientRect();
  const width = document.body.scrollWidth;
  //x,计算右侧位置够不够
  tip.style.left = e.clientX + "px";
  tip.style.left =
    width - e.clientX >= rectTip.width
      ? e.clientX + "px"
      : width - rectTip.width + "px";
  //y 计算上面位置
  let top = rectTarget.top - rectTip.height - 5;
  if (top < 0) {
    top = rectTarget.top + rectTarget.height + 5;
  }
  tip.style.top = top + "px";
}

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.