如何仅实现Ctrl + Contenteditable属性的功能? [英] How to Achieve Just the Ctrl + A Functionality of Contenteditable Attribute?

查看:61
本文介绍了如何仅实现Ctrl + Contenteditable属性的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为div显示一些示例代码供用户使用.我希望他们能够在div内进行选择,并使用Ctrl + A选择所有示例代码,但是我不希望他们能够编辑实际的文本(不要随意删除,然后再删除它)将无法正常工作.)

I'm trying to display a div with some example code for users. I want them to be able to select inside the div and use Ctrl + A to select all of the example code, but I don't want them to be able to edit the actual text (lest the remove a bit on accident and then it won't work).

我现在正在通过div上的contenteditable设置实现这一目标,但是在没有实际文本编辑的情况下,如何获得该属性的相同功能?

I'm achieving this right now through contenteditable set on the div, but how do I get the same functionality of this attribute sans the actual text editing?

编辑:查看 @先生中链接的解决方案.骆驼评论,我可以使用这种方法来实现所需的主要功能.但是,如果可能的话,我只想允许用户熟悉的Ctrl + A命令,并且仍然允许手动突出显示div文本的摘要.同样,所有这些都不允许添加或删除任何文本.

Looking at the solution linked in @Mr. Llama's comment, I can use this method to achieve the primary functionality I'm looking for. However, if possible I would like to simply allow for the Ctrl + A command my users are familiar with, and still allow for the manual highlighting of snippets of the div's text. Again, all while disallowing the addition or removal of any text.

推荐答案

当我防止onkeydownoncutonpaste事件时,似乎对我有用.

Seems to work for me when I prevent the onkeydown, oncut and onpaste events.

for (const elm of document.getElementsByClassName('editable-not-editable')) {
  elm.setAttribute('contenteditable', true);
  elm.spellcheck = false;
  elm.oncut = () => false;
  elm.onpaste = () => false;
  elm.onkeydown = (event) => {
    if (event.metaKey || event.ctrlKey) {
      return;
    }
    event.preventDefault();
  }
}

<div class="editable-not-editable">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor 
  incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud 
  exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute 
  irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla 
  pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia 
  deserunt mollit anim id est laborum.
</div>

这篇关于如何仅实现Ctrl + Contenteditable属性的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆