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

自定义光标悬停按钮不触发grow效果问题求助

解决自定义光标悬停按钮不放大的问题

问题根源分析

  • 原代码中growCursor函数仅定义但未执行,导致按钮的鼠标事件从未绑定
  • 使用document.querySelector('.button')只能获取第一个按钮,无法作用于所有按钮
  • 第二次尝试中选择器错误(querySelectorAll('b')应为.button),且循环内错误地给数组而非单个按钮绑定事件
  • 未获取innerCursor元素,导致无法修改其类名

修正后的完整代码

HTML(无需修改)

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

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

<button class="button" type="button" value="1" id="1">1</button>
<button class="button" type="button" value="2" id="2">2</button>

CSS(无需修改)

.inner-cursor {
    position: fixed;
    left: 10px;
    width: 10px;
    height: 10px;
    transform: translate(-50%, -50%);
    background-color: #627CE4;
    border-radius: 50%;
    pointer-events: none;
    transition: width 0.5s, height 0.5s;
}

.outer-cursor {
   position: fixed;
   left: 10px;
   width: 25px;
   height: 25px;
   transform: translate(-50%, -50%);
   border: 1px solid #627CE4;
   border-radius: 50%; 
   pointer-events: none;
   transition: 0.1s;
}

.inner-cursor.grow{
    width: 25px;
    height: 25px;
    transition: width 0.5s, height 0.5s;
}

JavaScript(修正版)

// 获取所有需要的元素
let outerCursor = document.querySelector('.outer-cursor');
let innerCursor = document.querySelector('.inner-cursor');
let buttons = document.querySelectorAll('.button');

// 绑定鼠标移动事件,让光标跟随
document.addEventListener('mousemove', moveCursor);

function moveCursor(e){
    let x = e.clientX;
    let y = e.clientY;

    innerCursor.style.left = `${x}px`;
    innerCursor.style.top = `${y}px`;

    outerCursor.style.left = `${x}px`;
    outerCursor.style.top = `${y}px`;
}

// 给每个按钮绑定悬停事件
buttons.forEach(button => {
    button.addEventListener('mouseover', () => {
        innerCursor.classList.add('grow');
    });
    button.addEventListener('mouseleave', () => {
        innerCursor.classList.remove('grow');
    });
});

关键修改点说明

  1. 获取正确的元素:
    • 新增innerCursor的获取,确保能操作内部光标元素
    • 使用document.querySelectorAll('.button')获取所有按钮元素
  2. 正确绑定事件:
    • 移除无用的growCursor函数,直接遍历按钮数组,给每个按钮单独绑定mouseover和mouseleave事件
    • 循环内使用当前遍历的button元素绑定事件,而非原数组
  3. 确保事件生效:
    • 无需额外调用函数,页面加载后直接执行事件绑定逻辑,避免事件未绑定的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 05:17:26