javascript 单击按钮时切换焦点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31460446/
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
Toggle focus onclick of a button
提问by ShellZero
I have a form inside a panel. The panel opens and closes when a button is clicked. When the panel is opened [i.e., with the click of the button], I want to focus on the first input text box in the form which is inside the panel. When I close the panel [i.e., again clicking on the same button], I want to loose the focus from that input box.
我在面板中有一个表格。单击按钮时,面板会打开和关闭。当面板打开时 [即,单击按钮],我想关注面板内表单中的第一个输入文本框。当我关闭面板 [即,再次单击同一个按钮] 时,我想从该输入框中松开焦点。
So, in simple words, I want to toggle the focus on the text input box when the onclick event happens on the button.
所以,简单来说,我想在按钮上发生 onclick 事件时切换文本输入框的焦点。
I gave the input text box an id and did the following:
我给输入文本框一个 id 并执行以下操作:
<input type="text" id="code" placeholder="enter code">
Inside the script tag:
在脚本标签内:
$('.button-element').click(function(){ $('#code').focus();});
This makes the focus on the input text box but I want to remove the focus when I click the button again.
这使得焦点在输入文本框上,但是当我再次单击按钮时我想移除焦点。
Please help me with this.
请帮我解决一下这个。
Thank you.
谢谢你。
采纳答案by A. Wolff
You could use this snippet (tested on chrome):
您可以使用此代码段(在 chrome 上测试):
var $code = $('#code');
$('.button-element').on('mousedown', function () {
$(this).data('inputFocused', $code.is(":focus"));
}).click(function () {
if ($(this).data('inputFocused')) {
$code.blur();
} else {
$code.focus();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="code" placeholder="enter code">
<button class="button-element">btn</button>
回答by RedClover
I know this is a very late answer, but here is a solution which adds a new jQuery method.
我知道这是一个很晚的答案,但这里有一个解决方案,它添加了一个新的 jQuery 方法。
You can add this to top of your $.onready
:
您可以将此添加到您的顶部$.onready
:
jQuery.fn.toggleFocus = function(){
if (this.is(":focus")) {
this.blur();
} else {
this.focus();
}
}
Usage:
用法:
$(".button-element").toggleFocus()
回答by asmockler
Try this:
试试这个:
var code = $('#code');
$('.button-element').click(function() {
if(code.is(":focus")) {
code.blur();
} else {
code.focus();
}
});
回答by Nikhil Aggarwal
You can update your code to following
您可以将代码更新为以下
var focusInput = true;
$('.button-element').click(function(){
if(focusInput) {
$('#code').focus();
} else {
$('#code').blur();
}
focusInput = !focusInput;
});
回答by Varun
Since you have not given any HTML,you need to change the code according to your need.
由于您没有给出任何 HTML,您需要根据需要更改代码。
$('.button-element').click(function()
{
if($("#ID-of-panel").is(':visible'))
$('#code').blur();
else
$('#code').focus();
});