我创建了一个可以用javascript填充表单的按钮,但它只填充页面上的第一个输入。我希望它能填充闪烁的输入光标。我需要帮助。继承我的代码:
<script>
function autoFill() {
var input = document.getElementsByTagName("INPUT")[0]
input.value += "only works with the first input";
}
</script>
<input type="input">
<button type="button" onclick="autoFill()">fill it!</button>
<input type="input">
这将跟踪输入焦点,当点击按钮时,它将填充正确的控制。
// track current focus
let currFocus;
document.addEventListener('focusin', (e) => {
if (e.target.nodeName.toLowerCase() === 'input') currFocus = e.target;
});
function autoFill() {
if (currFocus) currFocus.value += "only works with the first input";
}
<input type="input">
<button type="button" onclick="autoFill()">fill it!</button>
<input type="input">
一种解决方案是使用input[type="input"]
通过另外的状态变量(即如下所示的document.querySelectorAll
)跟踪先前聚焦的lastFocus
元素。然后,当调用autoFill()
时,填充value
元素的lastFocus
(如果存在):
let lastFocus = ''
function autoFill() {
/* If a last focused input exists, populate it */
if (lastFocus) {
var input = document.querySelector('input:focus')
lastFocus.value += "only works with the first input";
}
}
/* Iterate each input element in document */
document.querySelectorAll('input[type="input"]').forEach(element => {
/* Add an "on focus" listener, which sets last focused input*/
element.addEventListener('focus', event => {
lastFocus = element;
});
});
<input type="input">
<button type="button" onclick="autoFill()">fill it!</button>
<input type="input">
希望有所帮助!
您可以使用事件focus
并通过属性Event.target
获取当前关注的元素。
接受函数addEventListener
用于绑定事件。
let focused;
Array.from(document.querySelectorAll("input")).forEach((input) => {
input.addEventListener('focus', function(e) {
focused = e.target;
});
});
document.querySelector('button').addEventListener('click', () => {
if (focused) focused.value += "only works with the first input";
});
<input type="input">
<button type="button">fill it!</button>
<input type="input">
您始终在脚本中设置第一个输入控件的值。在单击自动填充按钮之前,您需要一种方法来识别哪个输入最后聚焦。也许你可以为每个必需的输入添加一个onfocus处理程序,并记录焦点的最后一个输入。
您需要一种方法来找出用户当前正在键入的输入框。我们可以通过将单击事件侦听器附加到各个文本框来完成此操作。只要有人点击它实际输入内容,我们就会更新一个全局变量,该变量包含对刚刚点击的引用 - 因此是活动的 - 对象。首先给你的文本框一个id,以便我们区分它们:
<input type="input" id="input1">
<input type="input" id="input2">
然后添加以下行:
var activeInput;
document.getElementById("input1").addEventListener("click", toggleActive);
document.getElementById("input2").addEventListener("click", toggleActive);
function autoFill() {
activeInput.value += "only works with the first input";
}
function toggleActive(e) {
activeInput = e.target;
}
我为焦点事件添加了监听器,并使用一个聚焦对象进行输入。
var focused, inputs=document.getElementsByTagName('INPUT');
for(i = 0; i < inputs.length; i++) {
inputs[i].addEventListener("focus", function(){
focused = this;
});
}
function autoFill() {
var input = document.getElementsByTagName("INPUT");
for(i = 0; i < input.length; i++) {
if(input[i] === focused){
input[i].value += "auto filled";
}
}
}
<input type="input">
<button type="button" onclick="autoFill()">fill it!</button>
<input type="input">