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

总结

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

相关推荐
信看3 小时前
NMEA-GNSS-RTK 定位html小工具
前端·javascript·html
爱吃大芒果3 小时前
Flutter 主题与深色模式:全局样式统一与动态切换
开发语言·javascript·flutter·ecmascript·gitcode
king王一帅4 小时前
流式渲染 Incremark、ant-design-x markdown、streammarkdown-vue 全流程方案对比
前端·javascript·人工智能
踢球的打工仔5 小时前
jquery的基本使用(3)
前端·javascript·jquery
徐同保6 小时前
js 点击按钮 把文本转成文件并下载下来
开发语言·javascript·ecmascript
bug总结6 小时前
前端开发中为什么要使用 URL().origin 提取接口根地址
开发语言·前端·javascript·vue.js·html
程序员爱钓鱼7 小时前
Node.js 编程实战:数据库连接池与性能优化
javascript·后端·node.js
Gomiko7 小时前
JavaScript DOM 原生部分(二):元素内容修改
开发语言·javascript·ecmascript
一招定胜负7 小时前
网络爬虫(第三部)
前端·javascript·爬虫