Vam*_*msi 15 html javascript jquery onblur
嗨我有一个包含三个文本框的div,我需要一个函数在控件超出div标签时被调用,我不想使用onclick事件,因为焦点可以通过按下来移出div键盘上的Tab键或其他方式.我还想知道是否有一种方法可以使用任何javascript库来实现这一点.
谢谢,这是示例html代码
<html>
<head>
<title>Div Onblur test</title>
<script type="text/javascript">
function Callme() {
alert("I am Called")
}
</script>
</head>
<body>
<div onblur="javascript:Callme();">
<input type=text value ="Inside DIV 1" />
<input type=text value ="Inside DIV 2" />
<input type=text value ="Inside DIV 3" />
</div>
<input type=text value ="Outside DIV" />
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
Bit*_*ter 10
您需要将tabindex = 0添加到div中才能获得焦点.所以像
<div tabindex="-1" onblur="Callme();">
Run Code Online (Sandbox Code Playgroud)
应该这样做.
您可以将onblur事件处理程序绑定到每个输入元素,并检查处理程序是否有任何焦点(使用document.activeElement).
<script type="text/javascript">
function checkBlur() {
setTimeout(function () {
if (document.activeElement != document.getElementById("input1") &&
document.activeElement != document.getElementById("input2") &&
document.activeElement != document.getElementById("input3")) {
alert("I am called");
}
}, 10);
}
</script>
<!-- ... -->
<div>
<input type="text" id="input1" value="Inside DIV 1" onblur="checkBlur()" />
<input type="text" id="input2" value="Inside DIV 2" onblur="checkBlur()" />
<input type="text" id="input3" value="Inside DIV 3" onblur="checkBlur()" />
</div>
<input type="text" value="Outside DIV" />
Run Code Online (Sandbox Code Playgroud)
或者,使用jQuery可以简化过程(特别是如果你有很多输入):
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#theDiv input").bind("blur", function () {
setTimeout(function () {
var isOut = true;
$("#theDiv input").each(function () {
if (this == document.activeElement) isOut = false;
});
if (isOut) {
// YOUR CODE HERE
alert("I am called");
}
}, 10);
});
});
</script>
<!-- ... -->
<div id="theDiv">
<input type="text" value="Inside DIV 1" />
<input type="text" value="Inside DIV 2" />
<input type="text" value="Inside DIV 3" />
</div>
<input type="text" value="Outside DIV" />
Run Code Online (Sandbox Code Playgroud)
编辑:我将事件处理程序包装在一个内部setTimeout,以确保其他元素有时间聚焦.
| 归档时间: |
|
| 查看次数: |
38386 次 |
| 最近记录: |