鼠标悬停按钮时仅在手机号长度为10时变色的实现报错排查
解决按钮悬停样式报错的问题
嘿,我来帮你拆解这个错误的根源,以及给出靠谱的修复方案。
首先,你碰到的Uncaught TypeError: Cannot set property 'backgroundColor' of undefined错误,问题直接出在你的JavaScript代码里:
if (phone.length!=10){ btn.onmouseover.style.backgroundColor="lightsalmon" } else{ btn.onmouseover.style.backgroundColor="chartreuse" btn.onmouseover.style.color="black" }
错误原因
btn.onmouseover指向的是你绑定的hovar函数本身,它并不是按钮元素的样式对象,所以你试图访问btn.onmouseover.style时,得到的是undefined,自然没法设置backgroundColor属性。我们要操作的是按钮元素(btn)本身的样式,而不是事件处理函数的属性。
修复方案
这里给你两种实用的修复方式,你可以根据需求选择:
方式一:直接操作按钮样式(快速修改)
先修改HTML里的按钮,去掉onmouseover属性(用事件监听更规范):
<button id="button">Register</button>
然后替换你的JavaScript代码:
const phoneInput = document.getElementById('ph_number'); const registerBtn = document.getElementById('button'); // 监听鼠标悬停事件 registerBtn.addEventListener('mouseover', function() { const phoneLength = phoneInput.value.trim().length; if (phoneLength === 10) { this.style.backgroundColor = 'chartreuse'; this.style.color = 'black'; } else { this.style.backgroundColor = 'lightsalmon'; this.style.color = 'aquamarine'; } }); // 鼠标离开时恢复默认样式,避免样式残留 registerBtn.addEventListener('mouseout', function() { this.style.backgroundColor = ''; this.style.color = ''; });
方式二:用CSS类控制(更推荐,样式与逻辑分离)
先修改CSS,把悬停样式拆成类:
#button{ font-size:20px; margin-left: 600px; border-radius: 8px; } /* 默认悬停样式(手机号长度不符合时) */ #button:hover { background-color: lightsalmon; color: aquamarine; } /* 手机号符合长度时的悬停样式 */ #button.valid-phone:hover { background-color: chartreuse; color: black; }
然后JavaScript监听手机号输入的变化,动态给按钮添加/移除类:
const phoneInput = document.getElementById('ph_number'); const registerBtn = document.getElementById('button'); // 监听手机号输入事件 phoneInput.addEventListener('input', function() { if (this.value.trim().length === 10) { registerBtn.classList.add('valid-phone'); } else { registerBtn.classList.remove('valid-phone'); } });
这种方式把样式逻辑放在CSS里,JS只负责类的切换,代码更清晰也更容易维护。
内容的提问来源于stack exchange,提问作者user14373544
相关产品推荐
相关产品推荐

