以下是JS实现鼠标移入显示气泡框的代码:

HTML代码:

<div id="bubble" class="hidden">这是气泡框</div>
<div id="target">鼠标移入显示气泡框</div>

CSS代码:

#bubble {
  position: absolute;
  background-color: #fff;
  border: 1px solid #ccc;
  padding: 10px;
  font-size: 14px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.2);
}

.hidden {
  display: none;
}

JS代码:

var target = document.getElementById("target");
var bubble = document.getElementById("bubble");

target.addEventListener("mouseover", function() {
  bubble.classList.remove("hidden");
});

target.addEventListener("mouseout", function() {
  bubble.classList.add("hidden");
});

target.addEventListener("mousemove", function(event) {
  bubble.style.left = event.clientX + "px";
  bubble.style.top = event.clientY + "px";
});

解释:

  1. 首先,我们获取鼠标移入的目标元素和要显示的气泡框元素。

  2. 然后,我们给目标元素绑定鼠标移入事件和鼠标移出事件,分别用来显示和隐藏气泡框。我们使用classList来添加和移除hidden类,这样就可以通过CSS来控制元素的显示和隐藏。

  3. 最后,我们给目标元素绑定鼠标移动事件,用来实时更新气泡框的位置。我们使用event.clientX和event.clientY获取鼠标的坐标,然后设置气泡框的left和top样式,这样气泡框就会跟随鼠标移动

JS写代码实现鼠标移入显示气泡框

原文地址: https://www.cveoy.top/t/topic/crlR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录