如何防止删除“部分” when editing?

问题描述 投票:0回答:1

如何防止用户在编辑过程中删除<div contenteditable>编辑器中的<section>(至少按“Delete”/“Backspace”键)?

<html>
<head>
	<title>Parcel Sandbox</title>
	<meta charset="UTF-8" />
	<style>
		#editor {
			width: 100%;
			height: 300px;
			border: 1px black solid;
		}
		#dont-remove-me-please{
			width: 100%;
			height: 100px;
			border: 1px red dashed;
		 font-weight: bold;
		 user-select: none;
		}
	</style>
</head>

<body>
	<div id="app"></div>

	<div contenteditable="true" id="editor">
		<div>hey guys!</div>
		<div><strong>more text...</strong></div>
		<section id="dont-remove-me-please" contenteditable="false">DONT' REMOVE ME!!!</section>
		<div><br></div>
	</div>
	<script>
		document.getElementById('editor').focus()
	</script>
</body>

</html>

谢谢。

javascript dom contenteditable
1个回答
0
投票

要获得预期的结果,请使用下面的click事件侦听器并根据id添加contenteditable属性

<script>
        document.getElementById('editor').addEventListener('click', function(e) { 
                     if(e.target.id !=="dont-remove-me-please"){
                         e.target.setAttribute("contentEditable", true);
                     }
                  }, false);
    </script>

代码示例 - https://codesandbox.io/s/rypy7wkn5m

<html>
<head>
	<title>Parcel Sandbox</title>
	<meta charset="UTF-8" />
	<style>
		#editor {
			width: 100%;
			height: 300px;
			border: 1px black solid;
		}
		#dont-remove-me-please{
			width: 100%;
			height: 100px;
			border: 1px red dashed;
		 font-weight: bold;
		 user-select: none;
		}
	</style>
</head>

<body>

	<div id="app"></div>

	<div id="editor">
		<div>hey guys!</div>
		<div><strong>more text...</strong></div>
		<section id="dont-remove-me-please" contenteditable="false">DONT' REMOVE ME!!!</section>
		<div><br></div>
	</div>
	<script>
		document.getElementById('editor').focus()
	</script>
		<script>
			document.getElementById('editor').addEventListener('click', function(e) { 
						 if(e.target.id !=="dont-remove-me-please"){
							 e.target.setAttribute("contentEditable", true);
						 }
					  }, false);
		</script>
</body>

</html>
© www.soinside.com 2019 - 2024. All rights reserved.