简体   繁体   English

如何在 Javascript 中更改 HTML 输入元素的焦点

[英]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.

相关问题 焦点对准时如何使用javascript设置(this)输入元素的样式 - How to style (this) input element with javascript when in focus 输入元素上的JavaScript更改事件仅在失去焦点时触发 - Javascript change event on input element fires on only losing focus 如何使用必需属性javascript / html / css填充输入时更改焦点颜色 - How to change focus color when input is filled in with required attribute javascript/html/css 如何将焦点更改为新的HTML5 Canvas元素? - How to change focus to new HTML5 Canvas element? 如何使用 JavaScript 将焦点设置在 HTML 表单中的元素上? - How can I set focus on an element in an HTML form using JavaScript? 如何在没有焦点的情况下使用javascript读取html页面中的输入 - How to read input in a html page with javascript without focus in one field 如何在JavaScript上访问HTML输入元素 - How to access HTML input element on javascript 如何在键盘上输入“ Enter”键 <input> 元素转移到下一个焦点 <input> 页面上的元素。 (JavaScript的) - How do I make “Enter” keypress in an <input> Element shift focus to the next <input> element on the page. (JavaScript) 更改焦点上输入元素的背景颜色 - Change the background color of an input element on focus 在html输入元素的焦点上触发数字键盘 - trigger number pad on focus in html input element
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM