【发布时间】:2013-08-30 16:57:37
【问题描述】:
我的网页中有 4 个文本框和一个提交按钮。 假设用户在 2 个字段中输入数据,然后单击提交按钮。 我现在想知道在单击提交按钮之前光标位于哪个文本框中。
知道如何在 Javascript 中执行此操作吗?
【问题讨论】:
-
document.activeElement 试试看
标签: javascript textbox dom-events
我的网页中有 4 个文本框和一个提交按钮。 假设用户在 2 个字段中输入数据,然后单击提交按钮。 我现在想知道在单击提交按钮之前光标位于哪个文本框中。
知道如何在 Javascript 中执行此操作吗?
【问题讨论】:
标签: javascript textbox dom-events
您正在寻找document.activeElement,它返回当前聚焦的元素。
【讨论】:
document.activeElement 正在返回 BODY 。但我想要第三个文本框的 NAME 。如何做到这一点。?
blur 事件并将最近的元素记录在一个变量中.
您的问题确实具体说 在 javascript 中,但 FWIW 是 jQuery 中的另一个选项:
HTML:
<input id="in1" type="text" /><br />
<input id="in2" type="text" /><br />
<input id="in3" type="text" /><br />
<input id="in4" type="text" /><br />
<input type="button" id="mybutt" value="Submit" />
jQuery:
var inFocus = false;
$('input, textarea').focus(function() {
inFocus = $(this).attr('id');
});
$('#mybutt').click(function() {
alert('Cursor was last in element id: ' + inFocus);
});
【讨论】:
你可以使用 document.activeElement
这是一个简单的例子。
<head>
<script type="text/javascript">
function GetActive () {
if (document.activeElement) {
var output = document.getElementById ("output");
output.innerHTML = document.activeElement.tagName;
}
}
</script>
</head>
<body onclick="GetActive ();">
Click anywhere on the page to get the active element
<input id="myInput" value="input field" />
<button>Sample button</button>
<div id="output"></div>
</body>
【讨论】: