问题描述
我有一个< input type =text>
字段,当这个字段失去焦点时我需要清除它(这意味着用户点击了某个地方页)。但有一个例外。当用户点击特定元素时,不应清除输入文本字段。
I have an <input type="text">
field and I need to clear it when this field loses focus (whiech means that user clicked somewhere on the page). But there is one exception. Input text field should't be cleared when user clicks on a specific element.
我尝试使用 event.relatedTarget
检测用户是否仅在某个地方点击了我的特定< div>
。
I tried to use event.relatedTarget
to detect if user clicked not just somewhere but on my specific <div>
.
但是你可以请参阅下面的代码段,它根本不起作用。 event.relatedTarget
总是返回 null
!
However as you can see in snippet below, it simply doesn't work. event.relatedTarget
is always returning null
!
function lose_focus(event) {
if(event.relatedTarget === null) {
document.getElementById('text-field').value = '';
}
}
.special {
width: 200px;
height: 100px;
background: #ccc;
border: 1px solid #000;
margin: 25px 0;
padding: 15px;
}
.special:hover {
cursor: pointer;
}
<input id="text-field" type="text" onblur="lose_focus(event)" placeholder="Type something...">
<div class="special">Clicking here should not cause clearing!</div>
推荐答案
简答:将 tabindex =0
属性添加到应出现在事件中的元素.relatedTarget
。
Short answer: add tabindex="0"
attribute to an element that should appear in event.relatedTarget
.
说明: event.relatedTarget
包含获得焦点的元素。问题是你的特定的 div无法获得焦点,因为浏览器认为这个元素不是按钮/字段或某种控制元素。
Explanation: event.relatedTarget
contains an element that gained focus. And the problem is that your specific div can't gain a focus because browser thinks that this element is not a button/field or some kind of a control element.
以下是默认情况下可以获得焦点的元素:
Here are the elements that can gain focus by default:
所以 event.relatedTarget
将在 onblur
发生时包含上述元素。 所有其他元素都不计算在内,点击它们会在 event.relatedTarget
null >。
So event.relatedTarget
will contain above elements when onblur
happens. All other elements will are not counted and clicking on them will put null
in event.relatedTarget
.
但是可以改变这种行为。您可以将DOM元素标记为可以通过 属性。以下是标准说法:
But it is possible to change this behaviour. You can 'mark' DOM element as element that can gain focus with tabindex attribute. Here is what standart says:
所以这里是更正的代码片段:
So here is the corrected code snippet:
function lose_focus(event) {
if(event.relatedTarget === null) {
document.getElementById('text-field').value = '';
}
}
.special {
width: 200px;
height: 100px;
background: #ccc;
border: 1px solid #000;
margin: 25px 0;
padding: 15px;
}
.special:hover {
cursor: pointer;
}
<input id="text-field" type="text" onblur="lose_focus(event)" placeholder="Type something...">
<div tabindex="0" class="special">Clicking here should not cause clearing!</div>
这篇关于blur event.relatedTarget返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!