【问题标题】:How to change the focus of an HTML input element in Javascript如何在 Javascript 中更改 HTML 输入元素的焦点
【发布时间】:2019-12-17 16:43:12
【问题描述】:

我有一个输入栏。当有人点击它时,我想改变那个输入栏的颜色,但我想用 Javascript 来做。我该怎么做?

【问题讨论】:

  • 所以添加一个焦点事件....
  • 有什么方法可以在纯香草 JS 中做到这一点?

标签: javascript focus


【解决方案1】:

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>

你可以添加一个模糊事件(是焦点的反转)

https://developer.mozilla.org/en-US/docs/Web/API/Element/blur_event

【讨论】:

  • 可以这样做,以便当我点击离开输入栏时,焦点消失了吗?
【解决方案2】:

这将使用纯 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>

它遍历每个 input 元素,添加两个事件侦听器,一个用于当它具有“焦点”时,一个用于当它失去焦点(“模糊”)时,它们会触发这些事件和样式他们。

【讨论】:

  • 这基本上是我想要的,但我需要在 javascript 中更改背景颜色,而不是 CSS。能做到吗?
  • 是的,我修改了代码以便它执行此操作。 .focus() 方法不再需要。
猜你喜欢
  • 2015-06-12
  • 1970-01-01
  • 2011-10-29
  • 2019-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-16
  • 2017-02-16
相关资源
最近更新 更多