You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JS为网页设置默认/指针模式的两种自定义PNG光标

解决自定义光标覆盖问题的方法

你之前的代码之所以只有最后一行生效,是因为两次给document.documentElement.style.cursor赋值,第二次会完全覆盖第一次的设置——元素的行内样式只能保留一个cursor属性值。

要实现默认箭头和指针手型分别用不同自定义光标,得通过全局CSS规则来定义,而不是直接修改行内样式。下面是可行的代码:

// 创建一个style标签
const customCursorStyle = document.createElement('style');
// 写入CSS规则:分别定义默认光标和指针光标
customCursorStyle.textContent = `
  /* 全局默认光标(替换原箭头) */
  html {
    cursor: url("https://www.happygourmet.co.uk/img/icon_plus.png"), default;
  }
  /* 所有需要手型光标的元素(替换原指针) */
  html a, 
  html button, 
  html [role="button"], 
  html input[type="submit"], 
  html input[type="button"],
  html label[for],
  html select,
  html option {
    cursor: url("https://img.icons8.com/emoji/72/camping.png"), pointer;
  }
`;
// 把style标签插入到页面头部
document.head.appendChild(customCursorStyle);

这段代码会在页面中插入全局样式:

  • 根元素<html>使用你指定的默认自定义光标,覆盖原箭头样式
  • 所有原本显示手型光标的元素(链接、按钮、表单控件等),替换为你设置的指针自定义光标

如果需要更全面覆盖所有pointer场景,也可以用:where选择器简化规则:

html :where(a, button, [role="button"], input[type="submit"], input[type="button"], label[for], select, option) {
  cursor: url("https://img.icons8.com/emoji/72/camping.png"), pointer;
}

内容的提问来源于stack exchange,提问作者Dany Maor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 12:00:22