javascript 仅在按下 Tab 键时调用 onBlur 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11881596/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 14:39:13  来源:igfitidea点击:

Call onBlur event only when tab key is pressed

javascriptasp.net

提问by raina

I have a textbox on which I want to execute onBlur event only when tab key is pressed to remove focus from textbox.

我有一个文本框,只有在按下 Tab 键以从文本框中移除焦点时,我才想在该文本框上执行 onBlur 事件。

How can I do this through javascript?

我怎样才能通过javascript做到这一点?

Any help is appreciated..

任何帮助表示赞赏..

回答by RobG

In browsers, pressing the tab key when a control has focus will move it to the next element in the tab order, causing the current element to lose focus and dispatch a blur event.

在浏览器中,当控件具有焦点时按下 tab 键会将其移动到 tab 顺序中的下一个元素,导致当前元素失去焦点并调度模糊事件。

Therefore you can just test for the pressing of the tab key and call your function based on that, e.g.

因此,您可以测试是否按下了 Tab 键并基于此调用您的函数,例如

<script type="text/javascript">

function showKey(e) {
  return e.which || e.keyCode;
}

</script>
<form>
  <input type="text" onkeydown="this.form.msg.value = showKey(event);">
  <input type="text" name="msg">
</form>

The above shows that the tab key has a value of 9, so you can do:

上面显示 tab 键的值为 9,因此您可以执行以下操作:

if ((e.which || e.keyCode) == 9) {
  // tab key was pressed, do stuff
}

Note that while most browsers support e.which, others e.keyCode.

请注意,虽然大多数浏览器支持 e.which,但其他浏览器支持 e.keyCode。

Edit

编辑

Based on your comment, the following shows that when the control loses focus, the value of the hidden field has been set:

根据您的评论,以下显示当控件失去焦点时,隐藏字段的值已设置:

  <input type="text" onkeydown="this.form.msg.value = showKey(event);
  (event);" onblur="alert(this.form.msg.value);">

回答by Rana Waqar

`enter code here`

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#theDiv input").bind("blur", function () {
            setTimeout(function () {
                var isOut = true;
                $("#theDiv input").each(function () {
                    if (this == document.activeElement) isOut = false;
                });
                if (isOut) {
                    // YOUR CODE HERE
                    alert("I am called");
                }
            }, 10);
        });
    });
</script>
<!-- ... -->
<div id="theDiv">
    <input type="text" value="Inside DIV 1" />
    <input type="text" value="Inside DIV 2" />
    <input type="text" value="Inside DIV 3" />
</div>
<input type="text" value="Outside DIV" />

回答by anagha

<script type="text/javascript">

function callfunc() {
 alert("Hello");
}

</script>


<form>
  <input type="text" onblur="callfunc();">
</form>