我有一个可聚焦的div,我想捕获键入事件,并防止在用户按下向下箭头或向上箭头时主体滚动。我打电话给preventDefault
和stopPropagation
,但它不起作用。
$('div').click((e) => e.focus())
$('div').on('keyup', (e) => {
e.stopPropagation();
e.preventDefault();
})
div {
border: 1px solid red;
width: 200px;
padding: 20px;
margin: 20px;
}
* {
box-sizing: border-box;
}
body {
height: 200vh;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div tabindex="0">Hey</div>
答案 0 :(得分:1)
仅使用keydown
个事件,不包含focus
如果按下的键是40
,也要加上arrow down
$('div').keydown(function(e) {
if(e.which==40){
e.stopPropagation();
e.preventDefault();
}
});
div {
border: 1px solid red;
width: 200px;
padding: 20px;
margin: 20px;
}
* {
box-sizing: border-box;
}
body {
height: 200vh;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div tabindex="0">Hey</div>