gpt4 book ai didi

javascript - 在Vue中使用箭头键选择div元素

转载 作者:行者123 更新时间:2023-11-28 12:15:43 25 4
gpt4 key购买 nike

我正在尝试使用箭头键浏览 div 元素。我知道如何用 JavaScript 实现它,但是我正在努力以“vue 方式”实现它。我知道不应该有任何差异,但它根本不起作用。

我已经做了sandbox以便您检查发生了什么事。如果我不使用 Vue

,它就可以工作

在 Vue 中,由于这一行,我收到以下错误:

Cannot read property 'focus' of null

document.activeElement.parentNode.previousSibling.firstChild.focus();

谁能告诉我我做错了什么? v-for 是错误源还是还有其他问题?

最佳答案

这实际上取决于您为什么需要焦点。如果只是为了突出显示某些内容,您可以使用辅助变量来跟踪当前突出显示的内容并向其添加一个类

https://codesandbox.io/s/300vxzkyk5

<template>
<div>
<input ref="input" type="text" @keydown="test" tabindex="0">
<div ref="test" v-for="item, index in items" :class="{ focus: index === focus }">
<div>{{ item.title }}</div>
</div>
</div>
</template>

<script>
export default {
data() {
return {
items: [
{ title: "First" },
{ title: "Second" },
{ title: "Third" }
],
focus: null
};
},
methods: {
test: function(event) {
switch (event.keyCode) {
case 38:
if (this.focus === null) {
this.focus = 0;
} else if (this.focus > 0) {
this.focus--;
}
break;
case 40:
if (this.focus === null) {
this.focus = 0;
} else if (this.focus < this.items.length - 1) {
this.focus++;
}
break;
}
}
}
};
</script>

<style>
div.focus {
border: 1px solid blue;
}
</style>

关于javascript - 在Vue中使用箭头键选择div元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49979574/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com