在 jQuery 中单击链接时如何防止 blur() 运行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7621711/
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
how to prevent blur() running when clicking a link in jQuery?
提问by Andrew Bullock
i have:
我有:
<input type="text" />
and
和
$('input').blur(function(){
alert('stay focused!');
});
I want to prevent the blur function running when I'm "blurring" by clicking on an anchor element.
我想通过单击锚元素来防止模糊功能在我“模糊”时运行。
I.E. if i tab to another input, click somewhere on the page etc i want the blur to fire, but if i click a link, I don't want it to fire.
IE 如果我标签到另一个输入,单击页面上的某处等我希望模糊触发,但如果我单击链接,我不希望它触发。
Is this easily achievable, or do i need to hack about with delegates and semaphores?
这是容易实现的,还是我需要用委托和信号量来破解?
Thanks
谢谢
回答by Alex B
I had to solve this problem myself today, too. I found that the mousedown event fires beforethe blur event, so all you need to do is set a variable that indicates that a mousedown event occurred first, and then manage your blur event appropriately if so.
我今天也必须自己解决这个问题。我发现 mousedown 事件在blur 事件之前触发,因此您需要做的就是设置一个变量,指示首先发生 mousedown 事件,然后在发生时适当地管理您的 blur 事件。
var mousedownHappened = false;
$('input').blur(function() {
if(mousedownHappened) // cancel the blur event
{
alert('stay focused!');
$('input').focus();
mousedownHappened = false;
}
else // blur event is okay
{
// Do stuff...
}
});
$('a').mousedown(function() {
mousedownHappened = true;
});
Hope this helps you!!
希望这对你有帮助!!
回答by Jens Jensen
If you want to keep the cursor at its position in a contenteditable
element, simply:
如果要将光标保持在contenteditable
元素中的位置,只需:
$('button').mousedown(function(){return false;});
回答by jfriend00
Delay the blur a bit. If the viewer clicks a link to another page, the page should change before this code gets a chance to run:
延迟模糊一点。如果查看者单击指向另一个页面的链接,则该页面应该在此代码有机会运行之前发生更改:
$('input').blur(function(){
setTimeout(function() {alert('stay focused!');}, 1000);
});
You can experiment with what delay value for the timeout seems appropriate.
您可以试验适合的超时延迟值。
回答by Scott Willeke
You can get this behavior by calling preventDefault()
in the mousedown
event of the control being clicked (that would otherwise take focus). For example:
您可以通过preventDefault()
在mousedown
单击控件的事件(否则将获得焦点)时调用来获得此行为。例如:
btn.addEventListener('mousedown', function (event) {
event.preventDefault()
})
btn.addEventListener('click', function(ev) {
input.value += '@'
input.setSelectionRange(ta.value.length, ta.value.length)
})
See live example here.
请参阅此处的现场示例。