如何点击表单元素时修改其背景颜色?附问题代码及尝试方案
解决点击输入框修改背景颜色的问题
先指出你代码里的几个问题:
document.queryselector拼写错误,正确写法是驼峰式的document.querySelector- CSS选择器语法错误,选择
type="text"的输入框应该用input[type="text"],而非input type="text" - 仅处理了第一个输入框,未给密码框添加点击事件
下面提供两种可行的解决方案:
方案一:单独选择每个输入框绑定事件
直接选中两个输入框,分别为它们添加点击事件:
<form id="form"> <input type="text" placeholder="text"/> <input type="password" placeholder="more text" /> </form> <script> // 选中text类型的输入框 const textInput = document.querySelector('input[type="text"]'); // 选中password类型的输入框 const passwordInput = document.querySelector('input[type="password"]'); // 点击text输入框时背景变绿色 textInput.addEventListener('click', () => { textInput.style.backgroundColor = 'green'; }); // 点击password输入框时背景变红色 passwordInput.addEventListener('click', () => { passwordInput.style.backgroundColor = 'red'; }); </script>
方案二:使用事件委托(适配多元素场景)
如果后续表单会新增更多输入框,事件委托更高效,只需给父元素form绑定一次事件:
<form id="form"> <input type="text" placeholder="text"/> <input type="password" placeholder="more text" /> </form> <script> const form = document.getElementById('form'); form.addEventListener('click', (e) => { // 判断点击的目标元素类型 if (e.target.type === 'text') { e.target.style.backgroundColor = 'green'; } else if (e.target.type === 'password') { e.target.style.backgroundColor = 'red'; } }); </script>
执行以上代码后,点击对应输入框即可触发背景颜色变化。
内容的提问来源于stack exchange,提问作者ninho
相关产品推荐
相关产品推荐

