简体   繁体   中英

How can I simulate a different button pressed when a button is pressed?

Is it possible using vue.js to simulate another button pressed when a button is pressed?

For example, if I press the (Arrow down) button, I would like it to be represented as if I had pressed the TAB button.

Explanation why am I trying to implement this:

After clicking on a DropDown list, the list with all the elements opens up. In this list I have an <input> element as a search box, which is used to search other elements in the list (all the other elements are directly listed under that search box). Currently as the DropDown list opens the focus is set automatically to the search box. To go down to the next item, you have to press the TAB button. But I need to achieve this with the (Arrow down) button.

I think you're asking how to simulate a TAB keypress when the user presses DOWN with the goal of moving the focus to the next focusable input.

Instead of rewriting the key -event, you could call HTMLElement#focus() on the next 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>

Sure, add a ref to tab

<div class="tab" ref="tab">

Then capture arrow click:

arrowClick() {
   this.$refs.tab.click()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM