JavaScript 选择自定义游标 (SVG)

javascript selecting a custom cursor (svg)

本文关键字:SVG 游标 选择 自定义 JavaScript      更新时间:2023-09-26

我在悬停时动态将光标更改为本地 svg

$(element).on('mouseover', function () {
    $(this).css('cursor', 'url(svgs/pointer.svg) 9 30 auto');
};

这工作正常,但我想选择该 svg 来操作其填充颜色。

有没有办法做到这一点,这样我就不必用不同的填充制作一堆不同的 svg?

谢谢

您可以使用内联 SVG。只需使用文本编辑器打开SVG文件即可。复制 XML 并改用它。只需更改填充值并将其重新分配给元素即可。

cursor: url('data:image/svg+xml;utf8,<svg fill="%23FF0000" height="48" viewBox="0 0 24 24" width="48" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"/><path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/></svg>') 24 24, auto;

使用此技术时,应转义数据中的特殊字符。有些人更喜欢 Base64 他们的图像,但对于 SVG,您不需要它。在上面的例子中,我只需要用%23替换填充值中的#

button {
  cursor: url('data:image/svg+xml;utf8,<svg fill="%23FF0000" height="48" viewBox="0 0 24 24" width="48" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"/><path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/></svg>') 24 24, auto;
}
button { padding: 30px; }
<button>Hover<br>Here</button>

> 除了@Dara提供的答案外,我还想补充一点,根据 SVG 的大小,curosor 可能会也可能不会在不同的浏览器中工作

button {
  padding: 30px;
}
#btnSmall {
  cursor: url('data:image/svg+xml;utf8,<svg fill="%23FF0000" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"/><path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/></svg>') 24 24, auto;
  background: mediumseagreen;
}
#btnLarge {
  cursor: url('data:image/svg+xml;utf8,<svg fill="%23FF0000" height="40" viewBox="0 0 24 24" width="40" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"/><path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/></svg>') 24 24, auto;
  background: orange;
}
#flex {
  display: flex;
  gap: 20px;
  text-align: center
}
#flex>div {
  padding: 5px;
  border: 1px solid darkgray;
  border-radius: 5px;
}
<div id="flex">
  <div>
    <p>Small SVG icons work</p>
    <button id="btnSmall">Hover<br>Here</button>
  </div>
  <div>
    <p>Large SVG icons don't work in chrome</p>
    <button id="btnLarge">Hover<br>Here</button>
  </div>
</div>

引用:

  • https://developer.mozilla.org/en-US/docs/Web/CSS/cursor#icon_size_limits
  • https://stackoverflow.com/a/46707611/6908282
  • https://stackoverflow.com/a/66428386/6908282
  • https://stackoverflow.com/a/45966695/6908282
  • https://stackoverflow.com/a/18551357/6908282