【前端】js vue 屏蔽BackSpace键删除键导致页面后退的方法

【前端】js vue 屏蔽BackSpace键删除键导致页面后退的方法

方法一:通过全局事件监听阻止 Backspace 导致页面后退

main.js 或组件的 mounted 中添加以下代码:

复制代码
//【前端】js vue 屏蔽BackSpace键删除键导致页面后退的方法
document.addEventListener('DOMContentLoaded', function () {
  document.body.addEventListener('keydown', function (e) {
    // 检查是否按下了Backspace键
    if (e.key === 'Backspace' || e.keyCode === 8) {
      // 如果焦点在一个可编辑的元素上(例如input或textarea),则允许Backspace键的操作
      const activeElement = document.activeElement;
      const isEditable = activeElement.tagName === 'INPUT' || activeElement.tagName === 'TEXTAREA' || activeElement.isContentEditable;

      if (isEditable) {
        return; // 允许Backspace操作
      }else{
        // 阻止默认行为
        e.preventDefault();
        alert('不能后退')
      }
    }
  });
});

方法二:使用 Vue 指令

如果你想在特定组件范围内阻止 Backspace 导致页面后退,可以创建一个自定义指令:

复制代码

javascript

复制代码

// 创建指令 Vue.directive('prevent-backspace', { bind(el) { el.addEventListener('keydown', (event) => { if (event.key === 'Backspace') { const target = event.target; const isInputElement = target.tagName === 'INPUT' || target.tagName === 'TEXTAREA'; const isEditable = target.isContentEditable; if (!isInputElement && !isEditable) { event.preventDefault(); } } }); } }); // 使用指令 <template> <div v-prevent-backspace> <!-- 页面内容 --> </div> </template>

方法三:使用 Vue Router 的 beforeEach 钩子

如果项目中启用了 Vue Router,可以结合路由导航守卫:

复制代码

javascript

复制代码

router.beforeEach((to, from, next) => { document.addEventListener('keydown', (event) => { if (event.key === 'Backspace') { const target = event.target; const isInputElement = target.tagName === 'INPUT' || target.tagName === 'TEXTAREA'; const isEditable = target.isContentEditable; if (!isInputElement && !isEditable) { event.preventDefault(); } } }); next(); });

注意

以上代码会阻止 Backspace 键在非输入区域时触发页面后退,同时保留在输入框或可编辑区域内的正常行为。如果有特殊场景,可以进一步自定义逻辑。

相关推荐
神奇的程序员2 小时前
开发了一个管理本地开发环境的软件
前端·flutter
天若有情6732 小时前
程序员原创|借鉴JS事件冒泡,根治电脑文件混乱的“冒泡整理法”
开发语言·javascript·windows·ecmascript·电脑·办公·日常
XiYang-DING3 小时前
HTML 核心标签
前端·html
特种加菲猫3 小时前
继承,一场跨越时空的对话
开发语言·c++
Csvn3 小时前
技术选型方法论
前端
Csvn3 小时前
前端架构演进:从页面到平台的十年变革
前端
李伟_Li慢慢3 小时前
ShaderToy-山峦+蓝天+白云
前端·webgl
小码哥_常3 小时前
Android字体字重设置全攻略:XML黑科技+Kotlin动态实现,告别.ttf臃肿
前端
FYKJ_20103 小时前
springboot校园兼职平台--附源码02041
java·javascript·spring boot·python·eclipse·django·php