![](/img/trans.png)
[英]How can I change multiple attributes of a form element when a button is clicked?
[英]How do i change the backgroundcolor of a form element when clicked?
我一直在試圖弄清楚如何在單擊表單元素時更改它的背景顏色。
繼承人的代碼:
<form id="form">
<input type="text" placeholder="text"/>
<input type="password" placeholder="more text" />
</form>
<script>
</script>
我正在嘗試使其顯示“文本”的表單元素在單擊時變為綠色,而顯示“更多文本”的表單元素在單擊時變為紅色。
我試過這個,但沒有奏效:
<script>
let form = document.queryselector('input type="text"');
form.addEventListener('click', () => {
form.style.backgroundColor = 'green'
});
</script>
我對編碼很陌生,所以非常感謝任何幫助! 謝謝!
如果您只想讓輸入背景在聚焦時改變顏色。 您可以通過使用 CSS 選擇器來實現此目的。 不需要 JS
input[type=text]:focus {
background-color: red;
}
或者,如果您希望更改表單背景
form:focus-within {
background-color:red;
}
問題在於這一行:
let form = document.queryselector('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>
請注意,一旦你聚焦,這不會改變背景顏色 - 你可能會更好地為focusout
, focusin
和可能blur
事件添加事件偵聽器 - 但更好的是,你可以使用 CSS:
form input[type="text"]:focus {
background-color: green;
}
你應該寫('input[type="text"]')
;
<script>
let form = document.querySelector('input[type="text"]');
form.addEventListener("click", () => {
form.style.backgroundColor = "green";
});
</script>
我建議在您的輸入標簽中添加和 Id 或 css class 然后您可以使用querySelector
--> https://www.w3schools.com/jsref/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.