我見過很多網站,可以通過按 Slash (Shift 7) 來聚焦搜索欄或類似內容。一個例子是MDN Web Docs。我想為我的 Vue 應用程式實作這個。Vue 檔案提到了最常用鍵的鍵修飾符,例如.enteror .tab,但沒有用于 Slash 的修飾符。此外,由于用戶應該能夠在頁面上的任何位置觸發事件,因此事件偵聽器不能應用于輸入元素本身。但是,我不知道如何將它應用到整個網站,因為 Vue 應用程式通常被注入到div正文中的一個或類似元素中。
uj5u.com熱心網友回復:
對于像這樣的邊緣情況,可以使用常規的 javascript 事件偵聽器。
您可以使用 Vue 生命周期方法來添加和洗掉偵聽器。這是一個作業示例:
Vue.createApp({
mounted() {
window.addEventListener("keypress", this.onKeyPress);
},
beforeDestroy() {
window.removeEventListener("keypress", this.onKeyPress);
},
methods: {
onKeyPress(event) {
if (event.key !== "/") {
return;
}
if (document.activeElement === this.$refs.searchInput) {
return;
}
event.preventDefault();
this.$refs.searchInput.focus();
}
}
}).mount('#app')
input {
padding: 0.75em 2em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.2.31/vue.global.min.js" integrity="sha512-C/bodwN49fOc1z jln 2l9FlJ lZ8HifB30oLE87zMQwsfoWv6Ed25b/x646tlcKb7515VJrJK8uo1oIH1UR2Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<div id="app">
<input type="search" ref="searchInput" placeholder="Press / to search" />
</div>
另一種解決方案可能是像v-hotkey這樣添加自定義指令的庫。
uj5u.com熱心網友回復:
<script src="https://unpkg.com/vue@3"></script>
<div id="app">
<input ref="input" />
</div>
<script>
Vue.createApp({
data() {
return {
show: true
}
},
mounted() {
window.addEventListener('keydown', (e) => {
if (e.key === '/' && this.$refs.input) {
e.preventDefault()
this.$refs.input.focus()
}
});
}
}).mount('#app')
</script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/448427.html
上一篇:vba中正則運算式模式的可選部分
