jQuery 有没有办法将 event.preventDefault 与 focusOut 一起使用?如果不是,为什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14613804/
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
Is there a way to use event.preventDefault with focusOut? If not, why?
提问by Klik
I would like to prevent the default event from a focusOut
(or blur
) event and keep the focus set to the specific input field.
我想阻止focusOut
(或blur
)事件的默认事件,并将焦点设置为特定的输入字段。
This is what I have already tried:
这是我已经尝试过的:
using
event.preventDefault()
at the beginning and at the end of the function (for test purposes, not for style)return false;
to prevent propagationsetting the focus back to the element directly in the element (but I found that the focus still switches because the focus switch is executed afterthe
.on()
function executes. I know I could usesetTimeout
, but I'd like to avoid it and figure out the heart of the issue.)using
blur
instead offocusOut
使用
event.preventDefault()
之初,在函数结束时(用于测试目的,而不是风格)return false;
防止传播直接在元素中将焦点设置回元素(但我发现焦点仍然切换,因为在函数执行后
.on()
执行焦点切换。我知道我可以使用setTimeout
,但我想避免它并弄清楚心脏的问题。)使用
blur
代替focusOut
My code is this:
我的代码是这样的:
_triggerEventHide: function(inst, eventType) {
inst.$target.on(eventType, function(event) {
event.preventDefault();
if (!$.suggestBox.$divCont.hasClass($.suggestBox.mouseOverClassName)) {
$.suggestBox.$divCont.css({display: 'none'}); //reposition Suggestbox
} else {
inst.target.focus();
}
event.preventDefault();
return false;
});
}
Note that $target
represents the jQuery-wrapped element and target
represents the native DOM element.
请注意,$target
表示 jQuery 包装的元素并target
表示本机 DOM 元素。
I've done some research and have found already a few articles relating to my question, but none of them answer this exact question.
我做了一些研究,已经找到了一些与我的问题相关的文章,但没有一篇文章回答了这个确切的问题。
preventDefault does not work on focus event– Here, the answer given is an alternate route to using any kind of event manipulation.
Focus back textbox on focus out if does not have required value– Here, the solution was to use
setTimeout()
to set the focus back to the original element, which is all right, but I'd like to understand the heart of the issue, whypreventDefault()
is not working here.jQuery preventDefault() not working – I tried some possible solutions from this thread, such as using
event.stopImmediatePropagation()
andevent.stop()
, but all for naught.
preventDefault 不适用于焦点事件——这里给出的答案是使用任何类型的事件操作的替代途径。
焦点焦点回到文本框出来,如果没有所需的值-在这里,解决方案是使用
setTimeout()
将焦点设置回原来的元素,这是所有的权利,但我想了解这个问题的心脏,为什么preventDefault()
是不在这里工作。jQuery preventDefault() 不起作用– 我尝试了该线程中的一些可能的解决方案,例如使用
event.stopImmediatePropagation()
andevent.stop()
,但都是徒劳的。
I appreciate any time, knowledge and solutions (including attempts) contributed in this matter. I would really like to learn…
我感谢在这件事上贡献的任何时间、知识和解决方案(包括尝试)。我真的很想学……
Here is a jsFiddleto show you the problem… feel free to play around with it and try different solutions.
这是一个 jsFiddle向您展示问题......随意尝试并尝试不同的解决方案。
回答by Klik
After some more research I've found out that only certain events are 'cancelable'.
经过更多研究,我发现只有某些事件是“可取消的”。
Quoted from http://help.dottoro.com/ljwolcsp.php
You can check whether an event can be canceled with the cancelable property in all browsers except in Internet Explorer before version 9. Although the cancelable property exists in Firefox, it always returns true, regardless of the cancelable state of the event. There is no way to determine whether an event can be canceled in Internet Explorer before version 9.
Note that the use of the preventDefault method and the returnValue property on a non-cancelable event does not cause an error. When an event handler returns false, the event will be canceled. You can use it instead of the preventDefault method and the returnValue property. See Example 2 below.
Each event in Javascript has a cancelable property that is defined as 'true' if the event can be prevented or 'false' if the event cannot be cancelled. Ref: http://help.dottoro.com/ljeosnqv.php
An example script from http://help.dottoro.com/ljeosnqv.phpdemonstrating this property can be found hereon jsFiddle (to save space). Note the comments in the code about how Firefox always returns true for the cancelable property in the event object.
引自http://help.dottoro.com/ljwolcsp.php
您可以在所有浏览器中使用cancelable 属性检查事件是否可以取消,但Internet Explorer 9 之前的版本除外。尽管Firefox 中存在cancelable 属性,但无论事件处于可取消状态,它始终返回true。无法确定是否可以在版本 9 之前的 Internet Explorer 中取消事件。
请注意,对不可取消事件使用 preventDefault 方法和 returnValue 属性不会导致错误。当事件处理程序返回 false 时,该事件将被取消。您可以使用它代替 preventDefault 方法和 returnValue 属性。请参见下面的示例 2。
Javascript 中的每个事件都有一个可取消的属性,如果事件可以被阻止,则定义为“true”,如果事件无法取消,则定义为“false”。参考:http: //help.dottoro.com/ljeosnqv.php
从一个示例脚本http://help.dottoro.com/ljeosnqv.php证明这个属性可以发现这里上的jsfiddle(为了节省空间)。请注意代码中关于 Firefox 如何始终为事件对象中的 cancelable 属性返回 true 的注释。
The general principal being:
一般原则是:
$('selector').on(eventType, function (event) {
alert(('cancelable' in event)); //will return true
alert(event.cancelable); //will return true if event can be cancelled
//NOTE: Firefox mistakenly always returns true
});
Events have a preset order of occuring depending on the situation. For example if a mouse button is clicked the order of eventTriggers would be: mousedown, mouseup, and click. Ref: www.w3.org/TR/DOM-Level-2-Events/events.html#Events-Event-initMouseEvent
Quoted from http://www.w3.org/TR/2003/NOTE-DOM-Level-3-Events-20031107/events.html#Events-flow-cancelation
A 'cancelable event' is an event associated with a default action which is allowed to be canceled during the DOM event flow. At any phase during the event flow, the triggered event listeners have the option of canceling the default action or allowing the default action to proceed. In the case of the hyperlink in the browser, canceling the action would have the result of not activating the hyperlink. Not all events defined in this specification are cancelable events.
Sometimes the sequence of events has it that the DOM default action will occur before the event you are looking to cancel even shows up, in these cases, you cannot cancel the default action because it has already taken place. That is to say the default action occurs beforethe dispatch of the event.
根据情况,事件具有预设的发生顺序。例如,如果单击鼠标按钮,则 eventTriggers 的顺序将是:mousedown、mouseup 和 click。参考:www.w3.org/TR/DOM-Level-2-Events/events.html#Events-Event-initMouseEvent
引自http://www.w3.org/TR/2003/NOTE-DOM-Level-3-Events-20031107/events.html#Events-flow-cancelation
“可取消事件”是与允许在 DOM 事件流期间取消的默认操作相关联的事件。在事件流的任何阶段,触发的事件侦听器都可以选择取消默认操作或允许执行默认操作。对于浏览器中的超链接,取消操作将导致不激活超链接。并非本规范中定义的所有事件都是可取消的事件。
有时,事件序列表明 DOM 默认操作将在您要取消的事件出现之前发生,在这些情况下,您无法取消默认操作,因为它已经发生。也就是说默认动作发生在事件调度之前。
MY SOLUTION:
我的解决方案:
That being said I did manage to find a solutionto my problem and more/less this problem. Essentially I had an eventListener with an element for focusin already and I wanted this element to keep focus.
话虽如此,我确实设法找到了解决我的问题的方法,并且或多或少地解决了这个问题。本质上,我已经有一个带有 focusin 元素的 eventListener,我希望这个元素保持焦点。
<div id='display'></div>
$('#idBox').on('focusin', function () {
$('#div').append('focused');
//do something
}
Initially I tried using a setTimeout event when I clicked off, but I found that wasn't good because it triggered my focusin event again. So what we need is an event that is dispatched before the DOM's default actionof switching focus. I did find that there isan event that meets this requirement, but is only available to IE... typical. For your information it is: "onbeforedeactivate"and it is cancelable. However since cross browser compatibility is important, we should not use this eventTrigger. Rather I found that the event mousedown occurs before the DOM starts its focus-changing behaviours.
最初,当我点击关闭时,我尝试使用 setTimeout 事件,但我发现这并不好,因为它再次触发了我的 focusin 事件。所以我们需要的是在 DOM 的默认切换焦点动作之前调度的事件。我也发现,有是符合这个要求的事件,但只适用于IE浏览器...典型。对于您的信息,它是:“onbeforedeactivate”并且它是可取消的。然而,由于跨浏览器兼容性很重要,我们不应该使用这个 eventTrigger。相反,我发现事件 mousedown 发生在 DOM 开始其焦点更改行为之前。
So what we could do is:
所以我们可以做的是:
$(document).on('mousedown', function(event) {
target = event.target; // the element clicked on
myTarget = document.getElementById("idBox"); // the element to keep focus
if (target !== myTarget) {
event.preventDefault(); //prevent default DOM action
event.stopPropagation(); //stop bubbling
return false; // return
}
});
There are many other ways of going about it. I personally don't like setting an eventListener to the entire document, but to demonstrate the basics it serves its purpose.
还有很多其他方法可以解决这个问题。我个人不喜欢为整个文档设置 eventListener,而是为了演示它的基本功能。
Footnote: A great article to read to learn more about event handling in Javascript is http://help.dottoro.com/ljtdqwlx.phpAn amazing resource I stumbled across.
脚注:http: //help.dottoro.com/ljtdqwlx.php 是一篇很棒的文章,可以阅读以了解有关 Javascript 中事件处理的更多信息,这是我偶然发现的一个了不起的资源。
回答by Easum
We know that it is the click function that cause the issue. So in the normal explorer like chrome, you can detact the mousedown event and then preventDefault.
我们知道是点击功能导致了问题。所以在像chrome这样的普通浏览器中,你可以检测mousedown事件,然后preventDefault。
But this doesn't work in ie, but we can use the beforedeactivate event instead http://msdn.microsoft.com/en-us/library/windows/apps/jj569321.aspx. It can be deteact in ie when the focus is changing. so just prevent it.
但这在 ie 中不起作用,但我们可以使用 beforedeactivate 事件代替http://msdn.microsoft.com/en-us/library/windows/apps/jj569321.aspx。当焦点改变时,它可以被检测到。所以只是阻止它。
code would like this:
代码是这样的:
$inp.on('blur', function(){
self.hide();
});
isIE && $inp.on('beforedeactivate', function(evt){
mousedown && evt.preventDefault();
});
$holder.on('mousedown', function(evt){
evt.preventDefault();
mousedown = 1;
});
回答by ROY Finley
inst.$target.on("blur", function() {
if (!$.suggestBox.$divCont.hasClass($.suggestBox.mouseOverClassName)) {
$.suggestBox.$divCont.css({'display': 'none'}); //reposition Suggestbox
return true;
}
inst.target.focus();
return false;
});
need to see your html. I don't think you are calling things correctly EX:
需要查看您的 html。我认为您没有正确地称呼事物 EX:
$.suggestBox
I think should be $(".suggestBox")
, but i cant tell without seeing your htnl
$.suggestBox
我想应该是$(".suggestBox")
,但没有看到你的 htnl 我无法判断