触发keydown事件需要控件获取到焦点,div控件无法像input控件那样获取到焦点,无法触发keydown事件,因此可以将keydown事件绑定在document上,然后用div的hover事件去判断鼠标是否正在div上。
<!DOCTYPE html><!--STATUS OK-->
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<meta http-equiv="content-type" content="text/htmlcharset=utf-8" />
<meta property="wb:webmaster" content="3aababe5ed22e23c" />
<meta name="referrer" content="always" />
<title>s鼠标悬浮事件嵌套键盘事件问题,点击空格并没有响应,求大神来帮助!_百度知道</title>
<style>
.divTest { width: 200px height: 200px border: 1px solid #CCC }
</style>
<script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
var divFocus = false
$(function () {
$(".divTest").hover(function () {
divFocus = true
$(".divTest").text(2)
}, function () {
divFocus = false
$(".divTest").text("")
})
$(document).keydown(function (event) {
if (!divFocus) {
return
}
if (event.keyCode != 32) {
return
}
$(".divTest").text(101)
})
})
</script>
</head>
<body>
<div class="divTest"></div>
</body>
</html>
<!DOCTYPE html ><html>
<head>
<meta http-equiv="Content-Type" content="text/html charset=UTF-8">
<title>RunJS 演示代码</title>
<script>
var c
var mo=function(){
c=setTimeout(function(){
alert("鼠标悬浮2秒才触发")
},2000)
}
var ct=function(){
clearTimeout(c)
}
</script>
</head>
<body>
<div onmouseover='mo()' onmouseout="ct()">
sdfsdfsdf
</div>
</body>
</html>