简体   繁体   English

单击时如何更改表单元素的背景颜色?

[英]How do i change the backgroundcolor of a form element when clicked?

I've been trying to figure out how I can change the background color of a form element when it is clicked on.我一直在试图弄清楚如何在单击表单元素时更改它的背景颜色。

Heres the code:继承人的代码:

<form id="form">

 <input type="text" placeholder="text"/>
<input type="password" placeholder="more text" />

</form>

<script>

</script>

I'm trying to make it so the form element where it says "text" turns green when clicked, and the form element where it says "more text" turns red when clicked.我正在尝试使其显示“文本”的表单元素在单击时变为绿色,而显示“更多文本”的表单元素在单击时变为红色。

I've tried this, which didn't work:我试过这个,但没有奏效:

<script>
let form = document.queryselector('input type="text"');

form.addEventListener('click', () => {

form.style.backgroundColor = 'green'

});
</script>

I'm very new to coding, so any help is very much appreciated!我对编码很陌生,所以非常感谢任何帮助! Thanks!谢谢!

If you just want the input background to change color while it's focused.如果您只想让输入背景在聚焦时改变颜色。 You can achieve this by using CSS selectors.您可以通过使用 CSS 选择器来实现此目的。 No need for JS不需要 JS

input[type=text]:focus {
  background-color: red;
}

Or if you want the form background to change或者,如果您希望更改表单背景

form:focus-within {
  background-color:red;
}

The issue is with this line:问题在于这一行:

let form = document.queryselector('input type="text"');

First of all - the querySelector() method is camel cased - note the capital S. Secondly, your selector is not quite correct - you're looking for: input[type="text"] :首先 - querySelector()方法是驼峰式的 - 请注意大写 S。其次,您的选择器不太正确 - 您正在寻找: input[type="text"]

 let form = document.querySelector('input[type="text"]'); form.addEventListener('click', () => { form.style.backgroundColor = 'green' });
 <form id="form"> <input type="text" placeholder="text"/> <input type="password" placeholder="more text" /> </form>

Notice though that this doesn't change the background colour back once you focus out - you might be better off adding event listeners for the focusout , focusin and maybe blur events - but better still, you can use CSS:请注意,一旦你聚焦,这不会改变背景颜色 - 你可能会更好地为focusoutfocusin和可能blur事件添加事件侦听器 - 但更好的是,你可以使用 CSS:

form input[type="text"]:focus {
  background-color: green;
}

you should write ('input[type="text"]') ;你应该写('input[type="text"]') ;

<script>
    let form = document.querySelector('input[type="text"]');

    form.addEventListener("click", () => {
      form.style.backgroundColor = "green";
    });
</script>

I would recommend add and Id or a css class into your input tag then you can use querySelector --> https://www.w3schools.com/jsref/met_document_queryselector.asp我建议在您的输入标签中添加和 Id 或 css class 然后您可以使用querySelector --> https://www.w3schools.com/jsref/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM