如何在 Javascript 中更改 HTML 输入元素的焦点
How to change the focus of an HTML input element in Javascript
我有一个输入栏。我想在有人点击它时更改该输入栏的颜色,但我想在 Javascript 中进行。我该怎么做?
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
这将更改带有普通 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 元素,添加两个事件侦听器,一个用于当它具有 "focus" 时,一个用于当它失去焦点时("blur" ),触发这些事件并设置它们的样式。
我有一个输入栏。我想在有人点击它时更改该输入栏的颜色,但我想在 Javascript 中进行。我该怎么做?
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
这将更改带有普通 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 元素,添加两个事件侦听器,一个用于当它具有 "focus" 时,一个用于当它失去焦点时("blur" ),触发这些事件并设置它们的样式。