【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()
}

总结

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

相关推荐
Never_Satisfied4 分钟前
在JavaScript / HTML / Node.js中,post方式的Content-Type属性的text的三种编码
javascript·node.js·html
Never_Satisfied26 分钟前
在JavaScript / HTML中,Chrome报错Refused to execute inline script
javascript·chrome·html
敲代码的嘎仔32 分钟前
JavaWeb零基础学习Day2——JS & Vue
java·开发语言·前端·javascript·数据结构·学习·算法
Keepreal4961 小时前
pdf文件预览实现
javascript·react.js
Asort1 小时前
JavaScript设计模式(九)——装饰器模式 (Decorator)
前端·javascript·设计模式
blazer2 小时前
前端团队CSS标准的AI化尝试:一次RAG技术的深度应用
javascript·llm·agent
小时前端2 小时前
🚀 面试必问的8道JavaScript异步难题:搞懂这些秒杀90%的候选人
javascript·面试
刘永胜是我2 小时前
解决React热更新中"process is not defined"错误:一个稳定可靠的方案
前端·javascript
悠哉摸鱼大王2 小时前
从麦克风输入到传输给后端实现ASR
前端·javascript
Takklin2 小时前
JavaScript 面试笔记:作用域、变量提升、暂时性死区与 const 的可变性
javascript·面试