javascript – blur event.relatedTarget返回null
作者:互联网
我有一个< input type =“text”>字段,当这个字段失去焦点时我需要清除它(这意味着用户点击了页面上的某个地方).但有一个例外.当用户单击特定元素时,不应清除输入文本字段.
我尝试使用event.relatedTarget来检测用户是否点击了某个地方而不是我的特定< div>.
但是正如您在下面的代码段中看到的那样,它根本不起作用. event.relatedTarget总是返回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”属性添加到应该出现在event.relatedTarget中的元素.
说明:event.relatedTarget包含获得焦点的元素.问题是你的特定div无法获得焦点,因为浏览器认为这个元素不是按钮/字段或某种控制元素.
以下是默认情况下可以获得焦点的元素:
<a>
elements withhref
attribute specified<link>
elements withhref
attribute specified<button>
elements<input>
elements that are nothidden
<select>
elements<textarea>
elements<menuitem>
elements- elements with attribue
draggable
<audio>
and<video>
elements withcontrols
attribute specified
因此,当onblur发生时,event.relatedTarget将包含上述元素.将不计算所有其他元素,单击它们将在event.relatedTarget中放置null.
但是有可能改变这种行为.您可以将DOM元素“标记”为可以使用tabindex属性获得焦点的元素.以下是标准说法:
The
tabindex
content attribute allows authors to indicate that an element is supposed to be focusable, whether it is supposed to be reachable using sequential focus navigation and, optionally, to suggest where in the sequential focus navigation order the element appears.
所以这是更正的代码片段:
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>
标签:onblur,javascript,events,lost-focus,focusout 来源: https://codeday.me/bug/20191004/1853546.html