div内容可编辑但只读 [英] div contentEditable but Readonly

查看:727
本文介绍了div内容可编辑但只读的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有一些文本的div,当光标悬停在这个div上选择文本时我想要。如果我让这个div保持原样,当试图选择全部(CTRL + A)时,我选择所有页面内容,即所有正文文本。



这个,我需要为这个div使用contenteditable属性。



但我不想让人们改变文本/复制/剪切等等



我尝试使用readonly for this div,但不起作用。



有什么建议吗?



PS1:这个div也有其他标签(html内容),但我不认为这是一个问题。



< PS2:一个例子是在这里:jsfiddle.net/msakamoto_sf/wfae8hzv/ - 但有一个问题。您可以剪切文本:(


解决方案

您可以通过处理剪切事件并调用其 preventDefault()方法。这将防止任何用户输入(包括浏览器的上下文菜单或编辑菜单)的剪切,而不仅仅是通过特定的组合键。



此示例使用jQuery,因为您的jsFiddle使用它:

  $(#editablediv) .on(cut,function(e){
e.preventDefault();
});


I have a div with some text and I want when the cursor is hover this div to select the text. If I let this div as it is, when trying to select all (CTRL+A) then I select all page content, meaning all body text.

To get rid of this, I need to use contenteditable attribute for this div.

But I don't want to let people to change the text / copy / cut and so on

I try to use readonly for this div, but doesn't working.

Any advice please ?

PS1: This div has also other tags inside (html content), but I don't think that this is a problem.

PS2: An example is here: jsfiddle.net/msakamoto_sf/wfae8hzv/ - but with a problem. You can cut the text :(

解决方案

You can prevent the user from cutting by handling the "cut" event and calling its preventDefault() method. This will prevent cut with any user input (including the browser's context menu or edit menu), not just via a particular key combination.

This example uses jQuery because your jsFiddle uses it:

$("#editablediv").on("cut", function(e) {
    e.preventDefault();
});

这篇关于div内容可编辑但只读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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