div contentEditable but Readonly

…衆ロ難τιáo~ 提交于 2020-04-09 07:46:26

问题


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 :(


回答1:


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();
});



回答2:


Use event.metaKey in the keydown event to check if ctrl (or cmd on mac) keys are being pressed. You also have to disable the cut and paste events.

<div
  contenteditable="true"
  oncut="return false"
  onpaste="return false"
  onkeydown="if(event.metaKey) return true; return false;">
    content goes here
</div>



回答3:


To prevent ctrl + x (Cut) from div you need to use following JQuery :

if (event.ctrlKey && event.keyCode === 88) 
{
   return false;
}

It will prevent to cut text from div.

Check Fiddle Here.




回答4:


set contenteditable to false and it should work !! that simple.

use contenteditable attribute for div to make it editable or not and use readonly attr for form input elements.

<element contenteditable="true|false">

<input readonly="readonly" />



回答5:


Here's an example in React, but it would work with basic HTML and JavaScript as well because I'm just leveraging the default events.

// import CSS
import './DefaultSettings.css';

// import packages
import React, { Component } from 'react';

// import components

const noop = (e) => {
  e.preventDefault();
  return false;
};

class DefaultSettings extends Component {
  render() {
    return (
      <div className="DefaultSettings"
        contentEditable={true}
        onCut={noop}
        onCopy={noop}
        onPaste={noop}
        onKeyDown={noop}>
      </div>
    );
  }
}

export default DefaultSettings;



回答6:


for JavaScript,

document.getElementById(divid).contentEditable = "false";

this will work



来源:https://stackoverflow.com/questions/30273377/div-contenteditable-but-readonly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!