首页 > 解决方案 > 如何在锚标记悬停时缩放我的自定义光标

问题描述

我用 html、css 和 js 创建了一个自定义光标。每当我将鼠标悬停在<a></a> 网页上的任何元素上时,我都希望光标扩大其正常宽度。任何人都可以快速提示如何使用它

下面是html、css和js

HTML

<div class="cursor-custom"></div>

CSS

.cursor-custom {
  width: 20px;
  height: 20px;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border: 1px solid rgba(0, 0, 0, 0.781);
  // background-color: rgba(0, 0, 0, 0.877);
  border-radius: 50%;
  // z-index: 2;
  transition-duration: 150ms;
  transition-timing-function: ease-out;
}```

JS

```$("* a").hover(function(){
  $("cursor-custom").css({
   "width" : "40px;",
   "height" : "40px;"
  });
  })

我尝试使用 javascript 悬停状态来更改自定义光标的大小,但它不起作用

标签: javascripthtmlcss

解决方案


规范中没有任何内容允许您更改加载的自定义光标的大小。

相反,您可以制作另一个光标图像文件的副本,在图像编辑器中调整它的大小,然后在将鼠标悬停在链接上时交换使用的光标文件,例如

body {
    cursor: url("cursor.png");
}

a {
    cursor: url("cursor-big.png");
}

由于 OP 现在已经澄清他们的光标是通过 JS 而不是 CSS 处理的,所以问题发生了一些变化。

主要是弄清楚“我们是否在悬停<a>标签”。我们可以通过该方法找到这一点,该Event.composedPath()方法以数组的形式给出,其中包含被悬停的元素的完整自上而下的 HTML 结构。

这是一个例子:

let cursor = document.getElementById("cursor");
let size;
document.body.addEventListener("mousemove", (ev)=>{
    let path = ev.composedPath();
    
    if (path.some(x=>x.tagName == "A")) size = 20;
    else size = 10;
    
    cursor.style.left   = (ev.clientX - size/2) + "px";
    cursor.style.top    = (ev.clientY - size/2) + "px";
    cursor.style.width  = size + "px";
    cursor.style.height = size + "px";
});
body, html {
    height: 100%;
    box-sizing: border-box;
}

* {
    cursor: none;
}

#cursor {
    position: fixed;
    background-color: #03A9F4;
    pointer-events: none;
    border-radius: 50%;
    transition: width 0.2s linear, height 0.2s linear;
}
<div id="cursor"></div>
<h1>My article</h1>
<p>Some amazing content, and a <a href="https://www.google.com">link</a>!</p>


推荐阅读