首页 > 解决方案 > 如何使用 CSS/JS 制作鼠标轨迹以使元素仍然可点击?

问题描述

当鼠标移动时,我想有一个鼠标轨迹。路径应该由小图标/图像构建,随着时间的推移会失去容量。(为简单起见,我删除了演示中的容量转换代码)我试图产生这种效果,创建一个位于所有其他元素之上的网格。这个网格由带有背景图像的小 div 组成。每个 div 的不透明度设置为 0。视觉上该解决方案有效,但整个页面上的元素不再可点击。怎么可能有相同的视觉效果,但页面上的所有元素仍然是可点击的?

我试图使可点击元素的 z-index 高于网格元素的 z-index。然后这些元素是可点击的。但是后来他们身上并没有出现尾迹效应,这不是应该的样子。

我研究了一个解决方案,并在下面遇到了这些页面/教程,但它们没有为我的问题提供解决方案:

https://medium.com/@dailyfire/cursor-trails-3-simple-css-tricks-to-add-to-any-website-part-1-64750798583c

https://www.youtube.com/watch?v=rfpRZ2t_BrQ

Javascript\Jquery 鼠标光标 - 悬停项目时不一致

const body = document.getElementsByTagName("body")[0];
const mouseMovementContainer = document.createElement("div");

mouseMovementContainer.setAttribute("id", "mouseMovementContainer");
mouseMovementContainer.classList.add("mouseMovement");

body.insertBefore(mouseMovementContainer, body.firstChild);

createNewGrid();

function createNewGrid () {
    for(let i = 0; i <= 1000; i++){
        const square = createOneSquare();
        mouseMovementContainer.appendChild(square);
    }
}

function createOneSquare () {
    const div = document.createElement("div");
    div.classList.add("square");
    return div;
}
a{
  font-size: 40px;
}

.mouseMovement {
  background-color: transparent;
  position: fixed;
  z-index: 100;
  display:flex;
  flex-wrap: wrap;
}

.square {
  width: 40px;
  height: 40px;
  background-image: url("https://icon-library.com/images/fire-icon-free/fire-icon-free-1.jpg");
  background-size: cover;
  opacity: 0;
}

.square:hover {
  opacity: 1;
}
<a href="https://www.google.com/">Go to Google!!!!</a>

标签: javascriptcss

解决方案


设置 z-index 有效

设置指针事件不起作用,因为 mousemove 也被删除了

.mouseMovement {
  background-color: transparent;
  position: fixed;
  z-index: 100;
  display:flex;
  flex-wrap: wrap;
  z-index: -1;  
}

const body = document.getElementsByTagName("body")[0];
const mouseMovementContainer = document.createElement("div");

mouseMovementContainer.setAttribute("id", "mouseMovementContainer");
mouseMovementContainer.classList.add("mouseMovement");

body.insertBefore(mouseMovementContainer, body.firstChild);

createNewGrid();

function createNewGrid () {
    for(let i = 0; i <= 1000; i++){
        const square = createOneSquare();
        mouseMovementContainer.appendChild(square);
    }
}

function createOneSquare () {
    const div = document.createElement("div");
    div.classList.add("square");
    return div;
}
a {
  font-size: 40px;
}

.mouseMovement {
  background-color: transparent;
  position: fixed;
  z-index: 100;
  display:flex;
  flex-wrap: wrap;
  z-index: -1;  
}

.square {
  width: 40px;
  height: 40px;
  background-image: url("https://icon-library.com/images/fire-icon-free/fire-icon-free-1.jpg");
  background-size: cover;
  opacity: 0;

}

.square:hover {
  opacity: 1;
}
<a href="https://www.google.com/">Go to Google!!!!</a>


推荐阅读