【js自定义鼠标样式】【js自定义鼠标动画】

文章目录


前言

自定义鼠标形状,自定义鼠标的动画,可以让我们的页面更加有设计感。

当前需求:吧鼠标自定义成一个正方形,鼠标的效果有:和页面的颜色做色差处理,例如当鼠标指到的颜色是白色,在鼠标的这块区域中显示的是黑色,另外,当鼠标指向特定区域时,正方形的鼠标放大三倍,并且以中心为圆点旋转。


一、效果图

鼠标放大之后的效果

鼠标没放大的效果

鼠标的色差

二、实现步骤

1. 去除原有鼠标样式

css 复制代码
body {
  cursor: none;
}

2. 自定义鼠标样式

代码如下(示例):

html 复制代码
<div id="mouse" class="mouse"></div>
css 复制代码
/* pointer-events: 取消它的鼠标事件,并指向它下面的元素。 */
/* mix-blend-mode: 设置图片元素与父容器背景(黄色)进行混合 */
.mouse {
  width: 30px;
  height: 30px;
  will-change: top, left; 
  position: fixed;
  left: -200px;
  z-index: 10020;
  pointer-events: none;
  mix-blend-mode: difference;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
}
/* 这是鼠标中的文字,可以不写 */
.mouse-text::after {
  content: "VIEW";
}

js如下

javascript 复制代码
// 引用gsap做动画
import gsap from 'gsap';

// 自定义鼠标样式
function setMouse() {
  const mouse = document.querySelector('.mouse');
  window.addEventListener('mousemove', function(event){    
    mouse.style.left = event.clientX - mouse.offsetWidth/2 + 'px';
    mouse.style.top = event.clientY - mouse.offsetHeight/2 + 'px';       
  })
  gsap.to("#mouse", {
    rotation: -30,
  });
}

// 鼠标动画(放大,旋转)
var mouseTl;

function setMouseChange1() {
  mouseTl = gsap.timeline();
  mouseTl.to("#mouse", {
    duration: .2,
    width: "150px",
    height: "150px"
  });
  mouseTl.fromTo("#mouse", {
    rotation: -30,
  },
  {
    duration: 7,
    repeat: -1,
    rotation: 330,
    ease: "none",
  });
  const mouseDiv = document.getElementById("mouse");
  mouseDiv.setAttribute("class", "mouse mouse-text");
}

// (缩小,旋转到原位)
function setMouseChange2() {
  mouseTl.pause(0);
  const mouseDiv = document.getElementById("mouse");
  mouseDiv.setAttribute("class", "mouse");
}

3. 使用

代码如下(示例):

html 复制代码
<div @mouseenter="bannerTextEnter" @mouseleave="bannerTextLeave">ANIMATION!</div>
javascript 复制代码
// 鼠标移动到banner文字事件
function bannerTextEnter() {
  setMouseChange1();
}
function bannerTextLeave() {
  setMouseChange2()
}

总结

以上就是自定义鼠标样式,自定义鼠标动画的全部了,如有疑问,请评论区留言。

相关推荐
To_OC5 小时前
LC 560 和为 K 的子数组:前缀和配哈希表,这对组合我是真的服了
javascript·算法·程序员
明朝百晓生6 小时前
Deep RL learning[2026/8]
开发语言·javascript·人工智能
用户938515635077 小时前
ESLint 代码规范完全指南——从 AST 原理到 flat config 逐行解析
javascript·后端·代码规范
kyriewen9 小时前
今年裁了16万技术人——但字节前端岗反而涨了23%
前端·javascript·面试
王林不想说话10 小时前
ES6 到 ES2026 全面进阶指南:新特性、原理、示例与工程落地
前端·javascript·面试
WZzz10 小时前
JavaScript 中 this 的「指向」完整教程
javascript
mONESY11 小时前
浏览器里跑 DeepSeek-R1,这份 worker.js 到底写了什么
javascript
用户69190268133911 小时前
用浏览器 WebGPU跑DPSK大模型(1) - 模型的下载和前端下载进度的显示
javascript·react.js·架构
夏幻灵11 小时前
Vue 2 与 Vue 3 在应用初始化上的设计差异与技术演进
前端·javascript·vue.js
悟空瞎说12 小时前
Three.js 架构实践:用 MVC 模式组织你的 3D 应用
前端·javascript