简体   繁体   English

如何在只读div中显示闪烁的文本光标/插入符号

[英]How to show blinking text cursor/caret in a read-only div

How can I show a blinking cursor (allowing for text selection via keyboard) in a div but keep it read-only (disallowing text input)? 如何在div中显示闪烁的光标(允许通过键盘选择文本)但保持只读(禁止文本输入)?

I know I can set contentEditable to enable the cursor on a div but then users can edit the contents. 我知道我可以设置contentEditable来启用div上的光标,然后用户可以编辑内容。 I've tried adding both contentEditable and readonly to the div but it seems readonly is only effective on input elements, like textarea or input. 我已经尝试将contentEditablereadonly添加到div中,但看起来readonly只对输入元素有效,如textarea或input。

I also have tried using a textarea and setting it to readonly so it shows the cursor but doesn't allow text input, like this: 我也尝试使用textarea并将其设置为只读,因此它显示光标但不允许文本输入,如下所示:

 <textarea readonly>Go ahead and move the cursor here but don't try to add text</textarea> 

This is the functionality I'm looking for but I want to do this with a div or some other non-input element. 这是我正在寻找的功能,但我想用div或其他非输入元素来做这个。 I'm open to using 3rd party libraries. 我愿意使用第三方库。


Note: "Cursor" or "caret" here is referring to the blinking lines that indicates where text selection starts/ends. 注意:这里的 “光标”或“插入符号”是指闪烁的行,指示文本选择的开始/结束位置。

Here you go :) . 干得好 :) 。 All you need to do is disable cut/copy/paste and key press events. 您需要做的就是禁用剪切/复制/粘贴和按键事件。

 <div contenteditable="true" oncut="return false" onpaste="return false" onkeydown="return false;" style="user-drag: none;" ondragenter="return false;" ondragleave="return false;" ondragover="return false;" ondrop="return false;"> Inner content </div> 

In Vanilla JavaScript, This is the simplest example of how you can go about doing it. 在Vanilla JavaScript中,这是你如何做到这一点的最简单的例子。 I am using a class here, but as other answers showed, you could change it to an actual attribute or whatever suits your linking. 我在这里使用了一个类,但正如其他答案所示,您可以将其更改为实际属性或任何适合您的链接。

  const uneditables = Array.from( document.querySelectorAll(".editable-but-not-really") ); const doNothing = e => e.preventDefault(); uneditables.forEach(element => { element.setAttribute("contentEditable", true); element.addEventListener("oncut", doNothing, false); element.addEventListener("onpaste", doNothing, false); element.addEventListener("keydown", doNothing, false); }); 
 <div class="editable-but-not-really">I am here to stay</div> <div class="editable-but-not-really">You cannot edit me</div> <div class="editable-but-not-really">I was born to stay</div> <div class="editable-but-not-really">As I am, and I don't</div> <div class="editable-but-not-really">want anything to do with</div> <div class="editable-but-not-really">your stinky pointer</div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM