使ContentEditable div只读? [英] Make a ContentEditable div read-only?
问题描述
所以我想要一个contenteditable的div的功能(通过键盘的文本选择是主要的),但我不想允许用户编辑文本 - 我推测 readonly =
So I want the features of a contenteditable div (text selection via keyboard being the main one), but I don't want to allow the user to edit the text - I presumed a readonly="readonly"
would work, but sadly it doesn't.
我们知道是否有办法做到这一点? contenteditable div在其中可以具有嵌套标签(< p>
,< h1>
)。
Do we know if there's a way to do it? The contenteditable div may have nested tags inside (<p>
's, <h1>
's).
我想避免使用textarea(这是为什么),因为它不允许我做其他我需要做的事情。
I want to avoid a textarea (that's what this is for), as it doesn't allow me to do other things I need to be able to do.
有没有javascript的好方法?如果没有,是否有一小段JavaScript代码仍然允许复制,突出显示等?
Is there a nice way to do this without javascript? And if there isn't, is there a small snippet of javascript that will still allow copying, highlighting etc?
谢谢。
以下是一个示例: http://codepen.io/anon/pen/dxeAE
推荐答案
我做了一个jQuery解决方案/解决方法。什么是防止在按下键时的默认操作:
I made a jquery solution/workaround. What is does is prevent the default action when a key is pressed:
$(document).ready(function(){
$("#editor").on("keypress", function(e) {
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="editor" contenteditable="">
<h1>PLEASE DO NOT USE THIS TEST!</h1>
<p>Maybe this will work. You should work this time, that's not nice that you don't work.qweqweqweqweqwe</p>
<p>qweqweqweqweqweqwe</p>
<p></p>
<h1>PLEASE DO NOT USE THIS TEST!</h1>
<p>Maybe this will work. You should work this time, that's not nice that you don't work.qweqweqweqweqwe</p>
<p>qweqweqweqweqweqwe</p>
<p></p>
<h1>PLEASE DO NOT USE THIS TEST!</h1>
<p>Maybe this will work. You should work this time, that's not nice that you don't work.qweqweqweqweqwe</p>
<p>qweqweqweqweqweqwe</p>
<p></p>
</div>
这篇关于使ContentEditable div只读?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!