[英]How to change the focus of an HTML input element in Javascript
I have an input bar.我有一个输入栏。 I'd like to change the color of that input bar when someone clicks on it, but I want to do it in Javascript.当有人点击它时,我想更改该输入栏的颜色,但我想在 Javascript 中进行。 How would I do this?我该怎么做?
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onfocus https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onfocus
<!DOCTYPE html> <html> <body> Enter your name: <input type="text" onfocus="myFunction(this)" id="abc" onblur="blured()"> <p>When the input field gets focus, a function is triggered which changes the background-color.</p> <script> function myFunction(x) { x.style.background = "yellow"; } function blured(x) { document.getElementById('abc').style.background = "white"; } </script> </body> </html>
You can add a blur event (is the inverse of focus)您可以添加模糊事件(与焦点相反)
https://developer.mozilla.org/en-US/docs/Web/API/Element/blur_event https://developer.mozilla.org/en-US/docs/Web/API/Element/blur_event
This will change the background color of the input with plain JavaScript and no CSS.这将使用纯 JavaScript 而没有 CSS 更改输入的背景颜色。
<input type="text">
<input type="text">
<input type="text">
<script>
var inp = document.getElementsByTagName('input');
for(var i = 0; i < inp.length; i++){
inp[i].addEventListener('focus', function(){
this.style.background = "red"
}.bind(inp[i]))
inp[i].addEventListener('blur', function(){
this.style.background = "none"
}.bind(inp[i]))
}
</script>
It loops through each input element, adds two event listeners, one for when it has "focus" and one for when it loses focus ("blur"), which fire on those events and styles them.它循环遍历每个输入元素,添加两个事件侦听器,一个用于“焦点”时,一个用于失去焦点(“模糊”)时,它们会触发这些事件并为其设置样式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.