属性
2023年09月07日
一、contenteditable
contenteditable
使 div
元素变成用户可编辑。
1.1 语法
<div contenteditable="true"></div>
1.2 场景
<style>
/* 输入框 */
.div-rich-editor {
width: 400px;
height: 400px;
border-radius: 4px;
background-color: #f5f5f5;
}
/* 输入框为空时显示 placeholder */
.div-rich-editor:empty:before {
content: attr(placeholder);
color: red;
}
/* 输入框获取焦点时移除 placeholder */
.div-rich-editor:focus:before {
content: none;
}
</style>
<div
class="div-rich-editor"
contenteditable="true"
placeholder="请输入内容"
onblur="onDivBlur(event)"
oninput="onDivInput(event)"
onpaste="onDivPaste(event)"
onkeydown="onDivKeyDown(event)"
onkeypress="onDivKeyPress(event)"
style="resize: both; overflow: auto"
></div>
<script>
function onDivInput(event){
const value = event.target.innerText;
console.log('onDivInput',value);
}
function onDivBlur(event){
const value = event.target.innerText;
console.log('onDivBlur',value);
}
function onDivPaste(event){
const value = event.originalEvent.clipboardData.getData('text');
console.log("onDivPaste",value)
}
function onDivKeyDown(event){
const value = event.target.innerText;
console.log('onDivKeyDown',value);
}
function onDivKeyPress(event){
const value = event.target.innerText;
console.log('onDivKeyDown',value);
}
</script>