发光文字跟随鼠标

效果展示

发光文字跟随鼠标_第1张图片

CSS / JavaScript 知识点

  • background-image 绘制网格背景
  • filter 属性的运用
  • onmousemove 事件运用
  • getBoundingClientRect 方法的运用

实现页面基础结构


<div class="cursour">div>

实现网格背景样式

body {
  min-height: 100vh;
  overflow: hidden;
  background: #222;
  /* 使用 linear-gradient 属性来绘制网格背景*/
  background-image: linear-gradient(to right, #333 1px, transparent 1px),
    linear-gradient(to bottom, #333 1px, transparent 1px);
  background-size: 40px 40px;
  cursor: none;
}

实现自定义光标

.cursour {
  position: fixed;
  width: 25px;
  height: 25px;
  border-top: 5px solid #0f0;
  border-left: 5px solid #0f0;
  transform-origin: top;
  transform: translate(-1px, 5px) rotate(15deg) scale(0);
  transition: transform 0.1s;
  pointer-events: none;
  filter: drop-shadow(0 0 5px #0f0) drop-shadow(0 0 15px #0f0) drop-shadow(
      0 0 35px #0f0
    ) hue-rotate(60deg);
}

.cursour::before {
  content: "";
  position: absolute;
  left: -2.5px;
  width: 5px;
  height: 40px;
  background: #0f0;
  transform-origin: top;
  transform: rotate(315deg);
}

实现移动光标移动并随机产生字母

let cursour = document.querySelector(".cursour");
let body = document.querySelector("body");

document.onmousemove = function (e) {
  // 根据鼠标的移动位置 重新设置自定义光标的位置
  cursour.style.top = e.pageY + "px";
  cursour.style.left = e.pageX + "px";

  // 重新设置网格背景的位置,从而达到视觉上感觉鼠标是在网格中移动
  body.style.backgroundPositionX = e.pageX / -4 + "px";
  body.style.backgroundPositionY = e.pageY / -4 + "px";

  // 创建字母容器
  let element = document.createElement("div");
  element.className = "element";
  body.prepend(element);

  element.style.left = cursour.getBoundingClientRect().x + "px";
  element.style.top = cursour.getBoundingClientRect().y - 20 + "px";

  // 创建对应的随机字母和样式设置
  setTimeout(() => {
    let text = document.querySelectorAll(".element")[0];

    directionX = Math.random() < 0.5 ? -1 : 1;
    directionY = Math.random() < 0.5 ? -1 : 1;

    text.style.left =
      parseInt(text.style.left) - directionX * (Math.random() * 200) + "px";
    text.style.top =
      parseInt(text.style.top) - directionX * (Math.random() * 200) + "px";
    text.style.opacity = 0;
    text.style.transform = "scale(0.25)";
    text.innerHTML = randomText();

    setTimeout(() => {
      element.remove();
    }, 1000);
  }, 10);
};

// 随机生成字母
function randomText() {
  const text = "abcdefghijklmnopqrstuvwxyz1234567890".split("");

  return text[parseInt(Math.random() * text.length)];
}

编写随机生成出的字母样式

.element {
  position: absolute;
  transform: translate(-50%, -50%);
  color: #0f0;
  pointer-events: none;
  width: 10px;
  height: 10px;
  transition: 1s;
  font-size: 2em;
  filter: drop-shadow(0 0 5px #0f0) drop-shadow(0 0 25px #0f0) hue-rotate(60deg);
}

完整代码下载

完整代码下载

你可能感兴趣的:(CSS,css3,前端)