是否可以使用 vue.js 在按下按钮时模拟按下另一个按钮?
例如,如果我按下 ↓(向下箭头)按钮,我希望它被表示为好像我按下了 TAB 按钮。
解释我为什么要尝试实现这个:
单击下拉列表后,将打开包含所有元素的列表。在此列表中,我有一个 <input>
元素作为搜索框,用于搜索列表中的其他元素(所有其他元素都直接列在该搜索框下)。目前,当下拉列表打开时,焦点会自动设置到搜索框。要转到下一个项目,您必须按 TAB 按钮。但我需要使用 ↓(向下箭头)按钮来实现这一点。
最佳答案
我认为您是在问如何在用户按下 DOWN 时模拟 TAB 按键,目的是将焦点移至下一个可聚焦输入。
您可以调用 HTMLElement#focus()
而不是重写 key
事件在下一个 sibling 上:
<!-- TEMPLATE -->
<input type="text"
@keydown.up.stop.prevent="prevInput"
@keydown.down.stop.prevent="nextInput"
v-for="i in 5">
// SCRIPT
methods: {
nextInput(e) {
const next = e.currentTarget.nextElementSibling;
if (next) {
next.focus();
}
},
prevInput(e) {
const prev = e.currentTarget.previousElementSibling;
if (prev) {
prev.focus();
}
},
}
<script src="https://unpkg.com/vue@2.5.17"></script>
<div id="app">
<input type="text"
@keydown.up.stop.prevent="prevInput"
@keydown.down.stop.prevent="nextInput"
v-for="i in 5">
</div>
<script>
new Vue({
el: '#app',
methods: {
nextInput(e) {
const next = e.currentTarget.nextElementSibling;
if (next) {
next.focus();
}
},
prevInput(e) {
const prev = e.currentTarget.previousElementSibling;
if (prev) {
prev.focus();
}
},
}
})
</script>
关于javascript - 按下按钮时如何模拟按下不同的按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52449306/