【问题标题】:In which TextBox is the cursor.?光标在哪个 TextBox 中。?
【发布时间】:2013-08-30 16:57:37
【问题描述】:

我的网页中有 4 个文本框和一个提交按钮。 假设用户在 2 个字段中输入数据,然后单击提交按钮。 我现在想知道在单击提交按钮之前光标位于哪个文本框中。

知道如何在 Javascript 中执行此操作吗?

【问题讨论】:

  • document.activeElement 试试看

标签: javascript textbox dom-events


【解决方案1】:

您正在寻找document.activeElement,它返回当前聚焦的元素。

【讨论】:

  • 我在第三个文本框中输入了数据并点击了提交按钮。现在 document.activeElement 正在返回 BODY 。但我想要第三个文本框的 NAME 。如何做到这一点。?
  • @Narendra:如果您想知道哪个元素最近处于活动状态,请处理所有元素的blur 事件并将最近的元素记录在一个变量中.
  • @Narendra Document 对象的 activeElement 属性必须返回文档中被聚焦的元素。如果 Document 中没有元素被聚焦,则必须返回 body 元素。 Source: HTML Living Standard - Updated 30 August 2013
【解决方案2】:

您的问题确实具体说 在 javascript 中,但 FWIW 是 jQuery 中的另一个选项:

Working jsFiddle here

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);
});

【讨论】:

  • 正是我想要的。辉煌...!谢谢..!!
【解决方案3】:

你可以使用 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-18
    • 1970-01-01
    • 2022-01-21
    • 2010-09-09
    • 1970-01-01
    • 2018-05-31
    • 2016-05-06
    • 1970-01-01
    相关资源
    最近更新 更多