如何在jQuery中设置焦点?在focusout事件中,我一直试图将焦点保持在控件上,但它似乎不起作用。
$(function() {
$("#Line1").focusout(function() {
alert("YOU CAN'T LEAVE HERE");
$("#Line1").focus();
});
});我的特定应用程序试图在字段离开焦点时对其进行验证,如果验证失败,我希望焦点保持在该控件上。
发布于 2014-12-27 07:19:49
在google chrome中,上面的例子是有效的。
HTML
<table id="bz_eventtable" border="" cellspacing="1" cellpadding="2">
<tbody>
<tr>
<td class="bzHeading">Line 1:</td>
<td class="bzDataTT">
<input id="Line1" value="" maxlength="50" size="50" name="Line1"/>
</td>
</tr>
<tr id="errorLine1">
<td colspan="2">
<span>Error in Line 1</span>
</td>
</tr>
<tr>
<td class="bzHeading">Line 2:</td>
<td class="bzDataTT">
<input id="Line2" value="" maxlength="50" size="50" name="Line2"/>
</td>
</tr>
</tbody>
</table>JS
$(function() {
$("#errorLine1").hide();
$("#Line1").focusout(function() {
$("#errorLine1").show().delay(3000).fadeOut();
$("#Line1").focus();
});
});CSS
body {
font-family:Tahoma;
font-size : 8pt;
padding-left:10px;
}
input[type="text"] {
font-family:Tahoma;
font-size : 8pt;
width:150px;
}发布于 2014-12-27 07:24:46
不能在focusout事件中更改焦点,因为浏览器已经在更改焦点。在浏览器完成焦点更改后,您可以使用计时器将焦点改回:
$(function() {
$("#Line1").focusout(function() {
alert("YOU CAN'T LEAVE HERE");
window.setTimeout(function(){
$("#Line1").focus();
}, 0);
});
});演示:http://jsfiddle.net/Guffa/12j5jraa/6/
注意:你真的应该考虑是否有任何其他方法来完成你想要完成的事情。不允许用户离开字段的行为可能是非常恼人的!
https://stackoverflow.com/questions/27662908
复制相似问题