Uncaught TypeError报错:无法读取null的style属性排查
解决a标签鼠标移动动画的TypeError报错问题
报错信息
Uncaught TypeError: Cannot read properties of null (reading 'style') at HTMLAnchorElement.animateit animateit @
问题原因
报错核心是代码中this.querySelector('span')返回了null,却直接尝试访问span.style。因为你用document.querySelectorAll('a')选中了页面上所有<a>标签,若页面中存在其他没有嵌套<span>的<a>元素,当鼠标触发这些a标签的事件时,就会找不到span,进而抛出错误。
解决方案
有两种可靠的修复方式:
方案1:只给包含span的a标签绑定事件
直接修改选择器,只选中内部包含<span>的<a>标签,从根源避免绑定到无span的a标签上:
(function () { // 只选择包含span子元素的a标签 const aLink = document.querySelectorAll('a:has(span)'); const cursor = document.querySelector('.cursor'); const animateit = function (e) { const span = this.querySelector('span'); const { offsetX: x, offsetY: y } = e, { offsetWidth: width, offsetHeight: height } = this, move = 35, xMove = x / width * (move * 2) - move, yMove = y / height * (move * 2) - move; span.style.transform = `translate(${xMove}px, ${yMove}px)`; if (e.type === 'mouseleave') span.style.transform = ''; }; aLink.forEach(b => b.addEventListener('mousemove', animateit)); aLink.forEach(b => b.addEventListener('mouseleave', animateit)); })();
方案2:在事件函数中增加空值判断
在操作span之前先检查它是否存在,若不存在则直接退出函数,避免报错:
(function () { const aLink = document.querySelectorAll('a'); const cursor = document.querySelector('.cursor'); const animateit = function (e) { const span = this.querySelector('span'); // 新增:如果找不到span,直接返回 if (!span) return; const { offsetX: x, offsetY: y } = e, { offsetWidth: width, offsetHeight: height } = this, move = 35, xMove = x / width * (move * 2) - move, yMove = y / height * (move * 2) - move; span.style.transform = `translate(${xMove}px, ${yMove}px)`; if (e.type === 'mouseleave') span.style.transform = ''; }; aLink.forEach(b => b.addEventListener('mousemove', animateit)); aLink.forEach(b => b.addEventListener('mouseleave', animateit)); })();
额外说明
如果你的页面中确实只有提供的两个带span的a标签,那可能是JS代码执行时机的问题——DOM还没完全加载就执行了代码,导致querySelectorAll没选中元素。这种情况下可以把代码放到DOMContentLoaded事件中:
document.addEventListener('DOMContentLoaded', function() { // 原代码放在这里 });
内容的提问来源于stack exchange,提问作者Adithya Sambari
相关产品推荐
相关产品推荐

