在堆栈溢出中写问答时,如何禁用键绑定?

问题描述 投票:0回答:1

我正在使用Ctrl + k杀死shell和所有文本编辑器中当前点的行。

当我执行Ctrl + k以便在堆栈溢出中键入问题或答案时删除行时,我总是以删除行失败而告终。因此,Ctrl + k将其放入[enter code here]。

[[Q]在堆栈溢出中键入我的问题或答案或以某种方式更改键绑定时,有什么方法可以禁用键绑定吗?

stack-overflow key-bindings
1个回答
0
投票

您可以使用用户脚本执行此操作。

我为您创建了一个,它将使Stack Overflow上的Ctrl + K变为您惯用的行为:从光标剪切到行尾(如果浏览器允许,剪切到剪贴板)。

  1. FirefoxChrome安装Tampermonkey
  2. 单击工具栏中的Tampermonkey图标,然后选择“创建新脚本”
  3. 粘贴下面的脚本
  4. 单击保存按钮

脚本:

// ==UserScript==
// @name         Cut from cursor instead of creating code block
// @version      0.1
// @description  Cut from cursor on Ctrl+K on Stack Overflow instead of creating code
// @author       CherryDT
// @match        https://stackoverflow.com/*
// @grant        none
// ==/UserScript==

(function() {
  'use strict'

  document.addEventListener('keydown', e => {
    // If the key in question is Ctrl+K
    if (e.which === 75 && e.ctrlKey) {
      // Prevent Stack Overflow's default behavior
      e.stopImmediatePropagation()

      // If cursor is in a textarea or an input field...
      const field = document.activeElement
      if (field.tagName === 'TEXTAREA' || field.tagName === 'INPUT') {
        // Find the end of the current line
        let lineEnd = field.value.indexOf('\n', field.selectionStart)
        // ...in case there is no newline at the end...
        if (lineEnd === -1) lineEnd = field.value.length
        // ...in case there was a CRLF...
        if (lineEnd > 0 && field.value[lineEnd - 1] === '\r') lineEnd--

        // Select rest of line
        field.setSelectionRange(field.selectionStart, lineEnd)

        // Copy, if possible
        try {
          document.execCommand('copy')
        } catch (e) {
          console.warn('Failed to copy', e)
        }

        // Remove text
        field.setRangeText('', field.selectionStart, field.selectionEnd, 'start')

        // Prevent browser default action
        e.preventDefault()
      }
    }
  }, { capture: true }) // Handle in capture phase to be "faster" than Stack Overflow
})()

一些注意事项:

  • 如果要在all站点上而不是仅在Stack Overflow上发生此行为,请将@match行从https://stackoverflow.com/*更改为*://*/*
  • [如果您不想将剪切的文本移到剪贴板,而只是将其删除,则删除try块。
© www.soinside.com 2019 - 2024. All rights reserved.