JavaScript FocusOut-获取接收焦点的元素
当引发FocusOut事件时,您如何知道哪个元素接收焦点 正确的方法似乎是使用事件的relatedTarget属性。但是,这似乎并不适用于所有浏览器:JavaScript FocusOut-获取接收焦点的元素,javascript,focusout,Javascript,Focusout,当引发FocusOut事件时,您如何知道哪个元素接收焦点 正确的方法似乎是使用事件的relatedTarget属性。但是,这似乎并不适用于所有浏览器: 在谷歌Chrome中,它是有效的 在Firefox和Internet Explorer中,relatedTarget为空 在Safari中,relatedTarget属性甚至不存在 我已经找到了一个只在IE中工作的解决方案(使用document.activeElement),但我想知道是否有一个通用的解决方案可以在所有主流浏览器中工作 虽然我
- 在谷歌Chrome中,它是有效的
- 在Firefox和Internet Explorer中,relatedTarget为空
- 在Safari中,relatedTarget属性甚至不存在
document.getElementById('text1').addEventListener('focusout',函数(e){
//此时,我想知道哪个元素正在接收焦点(即text2)
console.log(e.relatedTarget);//在Chrome中工作
console.log(document.activeElement);//在IE中工作
//两者在Firefox或Safari中都不起作用
});代码>
我相信您要找的是document.activeElement
返回当前关注的元素,即如果用户键入任何击键事件,将获取击键事件的元素。此属性是只读的
我对firefox有一个假设和解决方法。document.activeElement似乎可以工作。然后focusout点击,所以它被移除。当focusin点击时(或之后),将再次出现一个聚焦元素。但在out和in之间并没有任何焦点,所以并没有任何元素被报告为活动的
我的解决方法是一个愚蠢的设置超时黑客<代码>设置超时(函数(){console.log(document.activeElement)},1)代码>可靠地为我获取一个活动元素。当然,我只在一台机器上进行了测试,并花费了90秒的时间,但这是迄今为止我发现的最好的测试。我在使用textEditor PrimeFaces元素时遇到了同样的问题
//attach a focus out handler
$("#id").focusOut($El_FocusOut);
//display the id of new element being focused onto
function $El_FocusOut($eventArgs){
//firefox specific focusout active element logi
var activeElement = $eventArgs.originalEvent.explicitOriginalTarget;
alert($(activeElement).attr("id"))
}
我使用以下html代码
<div contenteditable="true" class="div-focus">
<h:outputText
styleClass="OutputField"
value="#{oController.panelTpl.getComment()}"
escape="false"
/>
</div>
<div class="text-editor">
<p:textEditor
value="#{oController.panelTpl.txtComment.text}"
/>
</div>
加载页面时会调用onLoadDialog函数(),用于隐藏看起来合乎逻辑的内容,但在FocusOut事件处理程序中,它会在某些浏览器中返回Body元素(即使实际焦点从一个输入元素切换到下一个输入元素)。此外,我刚刚注意到您已经尝试了document.activeElement
。完全错过了。嗯,不是真的。我的具体情况是,我想知道包含其他元素的DIV何时会失去焦点。我想使用DIV的FocusOut事件,检查接收焦点的元素是否是这个DIV中的另一个元素。但是除了具体的问题之外,我只是好奇,对于这样一个简单的问题,是否没有跨浏览器的解决方案。啊。。。那么,也许一个例子会有所帮助。在这一点上,不管它值多少钱,它在Chrome、Firefox、Safari、IE和Opera中都能持续工作。是的,这是一种技巧。。。但它似乎在所有主流浏览器中都能工作!据我所知,只有当该元素的焦点丢失到另一个可以接收击键的元素(例如input、textarea)时,这才有效。对于其他内容,document.activeElement==document.body。
function onLoadDialog()
{
jQuery(".text-editor").hide();
jQuery(".div-focus").focusin(function()
{
$(this).hide();
$(this).next(".text-editor").show();
$(this).next(".text-editor").focus();
});
jQuery(".text-editor").focusout(function(e)
{
if ($(e.relatedTarget).closest(".text-editor").size() == 0)
{
$(this).hide();
$(this).prev(".div-focus").show();
$(this).prev(".div-focus").text($(this).text());
}
});
}