You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现光标移出页面时隐藏自定义Circle Cursor

解决圆形光标移出页面时不消失的问题

要实现鼠标移出页面时光标消失,只需监听页面的mouseleave和mouseenter事件,配合CSS控制光标显示状态即可,以下是修改后的完整代码:

修改后的CSS

@import url(/css/satoshi.css);
*,
*::before,
*::after {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: Satoshi-Variable;
}

html,
body {
  height: 100%;
  min-height: 100%;
}

body {
  background-color: #f0efe9;
  height: 100vh;
  width: 100%;
  cursor: none;
}

.cursor {
  height: 40px;
  width: 40px;
  border-radius: 50%;
  position: fixed;
  transform: translate(-50%, -50%);
  pointer-events: none;
  background: #f0efe9;
  mix-blend-mode: difference;
  /* 新增opacity过渡,让显示隐藏更平滑 */
  transition: width 0.1s linear, height 0.1s linear, opacity 0.1s linear;
}

/* 新增隐藏类 */
.cursor.hidden {
  opacity: 0;
}

body:has(a:hover) .cursor {
  transform: translate(-50%, -50%);
  height: 80px;
  width: 80px;
}

a {
  cursor: none;
  text-decoration: none;
  color: #0f1016;
}

div {
  border-spacing: 0;
  display: block;
}

.a1 {
  width: 50%;
  height: 25%;
}

.a2 {
  width: 60%;
  height: 50%;
}

.a3 {
  width: 50%;
  height: 25%;
}

.icon {
  padding: 5% 0 5% 10%;
  max-width: 40%;
}

.skills {
  font-family: Satoshi-Variable;
  font-weight: 600;
  font-size: 2em;
  padding-left: 10%;
  padding-top: 2%;
  padding-bottom: 2%;
  color: #0f1016;
}

.graphic_designer {
  margin-top: 2%;
  margin-bottom: 2%;
}

ul {
  list-style: none;
}

.about_me {
  padding-left: 10%;
  line-height: 2em;
  color: #0f1016;
}

修改后的JavaScript

const cursor = document.querySelector(".cursor");

window.addEventListener("mousemove", (e) => {
  let x = e.pageX - window.scrollX;
  let y = e.pageY - window.scrollY;

  cursor.style.left = `${x}px`;
  cursor.style.top = `${y}px`;
  // 移动时确保光标处于显示状态
  cursor.classList.remove("hidden");
});

// 鼠标移出页面视口时隐藏光标
window.addEventListener("mouseleave", () => {
  cursor.classList.add("hidden");
});

// 鼠标回到页面视口时显示光标
window.addEventListener("mouseenter", () => {
  cursor.classList.remove("hidden");
});

关键说明

  • 通过mouseleave事件监听鼠标离开页面的动作,给光标添加hidden类实现透明隐藏;
  • mouseenter事件监听鼠标返回页面的动作,移除hidden类恢复光标显示;
  • 在mousemove事件中也添加移除hidden的操作,避免快速进出页面后光标无法正常显示的边缘情况;
  • 使用opacity而非display: none来控制隐藏,是为了保留过渡动画效果,让光标显示/隐藏的变化更流畅,与现有缩放动画风格统一。

内容的提问来源于stack exchange,提问作者David M.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 10:15:16