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

如何解决a标签悬停切换类时触发Uncaught TypeError读取undefined属性错误

错误原因

你触发报错的核心原因是行内事件绑定调用函数时,this指向错误:
直接在onmouseover里写myFunction()的场景下,函数内部的this默认指向全局window对象,而window不存在classList属性,所以访问this.classList就会返回undefined,调用toggle方法自然就会抛出你遇到的类型错误。

修复方案

方案1:修改行内传参,成本最低

直接把当前元素作为参数传入函数即可:

  1. 修改HTML行内事件代码:
<a href="" target="_self" class="sticky-cta" onmouseover="myFunction(this)" >
  <span class="sticky-label">GET STARTED</span>
  <i class="icon-features-productivity"></i>
</a>
  1. 修改JS函数接收元素参数:
function myFunction (el) {
    el.classList.toggle("-js-expanded");
}

方案2:使用标准事件绑定,更易维护

不推荐使用行内事件属性,你可以移除HTML里的onmouseover属性,用JS统一绑定事件,此时this会自动指向触发事件的元素:

// 选中目标a标签
const stickyCta = document.querySelector('.sticky-cta');
// 绑定鼠标移入事件
stickyCta.addEventListener('mouseover', function() {
  this.classList.toggle('-js-expanded');
});
// 如果需要鼠标移出时自动移除类,可以补充下面的代码
stickyCta.addEventListener('mouseout', function() {
  this.classList.remove('-js-expanded');
});

你的CSS代码无需修改即可正常生效。

内容的提问来源于stack exchange,提问作者Khandaker Ajmain Ingqiyad

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 04:15:03