【问题标题】:Is this possible to write own hotkey for content editable in HTML Jquery?这是否可以为 HTML Jquery 中可编辑的内容编写自己的热键?
【发布时间】:2015-10-07 11:38:00
【问题描述】:

实际上,如果我们在内容可编辑中使用Ctrl+B,它会创建一个标签

<b>Content goes here... </b> like this.

我们可以添加自己的热键,例如

Ctrl+T

<a class="tamil">Content goes here...</a>

Ctrl+E

<a class="tamil">Content goes here...</a>

请帮忙解决这个问题,提前谢谢。

【问题讨论】:

  • 除了写伪代码,你有没有尝试过?另外,我会避免使用现有的组合键(Ctrl+T 打开一个新选项卡)。
  • 当然,我问了例子。如果组合键可用,我将更改组合。但我需要这个概念..
  • 我们不是来给你做东西的。向我们展示您尝试和/或研究的内容,我们可以帮助您实现您想要的。
  • 你听说过shortcut.js吗,请参考这个..openjs.com/scripts/events/keyboard_shortcuts
  • 不,您不能添加浏览器原生行为。不过你可以模拟它

标签: javascript jquery html css contenteditable


【解决方案1】:

使用 jQuery 非常简单:

您可以将 keydown-EventListener 添加到每个 contenteditable 元素(或只是 div,任何适合您的目的),您甚至可以在其中消除标准浏览器行为:

$('[contenteditable=true]').keydown(function(e){
    if(e.ctrlKey && e.keyCode == 70){
        e.preventDefault();
        $('#result').append('CTRL + F registered. ');
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div contenteditable=true>
    <p>Some text in here</p>    
</div>

<p id="result"></p>

这个事件监听器只有在 contenteditable 元素被聚焦时才会被触发,所以如果它没有被聚焦,你的组合键的标准浏览器功能仍然会被触发。

针对最新版本的 chrome、firefox 和 ie 进行了测试。

【讨论】:

    【解决方案2】:

    这是使用 ctrl+q 的完整工作代码

    $(document).keyup(function(e){
        if(e.ctrlKey && e.keyCode == 81){
    	  var selection= window.getSelection().getRangeAt(0);
          var selectedText = selection.extractContents();
          var anc= document.createElement("a");
          anc.setAttribute('id','tamil');
          anc.appendChild(selectedText);
          selection.insertNode(anc);
       }
    });
       
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    Here is a text to work with.

    【讨论】:

      猜你喜欢
      • 2013-01-14
      • 1970-01-01
      • 2010-10-06
      • 1970-01-01
      • 2021-08-26
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多