用習慣了前段的框架,反而會把最基本的東西給忘記了;
<div style="width:100px;height:200px;border:1px solid red" contenteditable></div>
之前一直覺得在div這個元素中實現編輯文字會很困難,會使用到各種js的操作之類的,一查發現自己想多了,只需要在div中添加contenteditable屬性即可;
注意:contenteditable是html5中新增加的屬性,用於規定元素是否可被編輯
實現了div文字編輯,那我們怎么獲取文字內容呢?
1.js操作:
<div style="width:100px;height:200px;border:1px solid red" contenteditable id="editContent" @click="getDivVal"></div>
getDivVal(){ console.log(document.getElementById('editContent').innerHTML)
console.log(document.getElementById('editContent').textContent)
},
主要是在div元素上綁定一個id值,然后通過js的文檔操作獲取到整個元素,之后再使用innerHTML/textContent獲取到值
注意:
1.innerHTML既可以獲取HTML中的文本內容,也可以在HTML元素中插入內容
document.getElementById('editContent').innerHTML=“我是張三”
-------------------------------------------------------------------------------------------------------------------------------------
再通過js操作獲取到元素中的數據時,不同的元素,所使用的api有不同,例如,對於input框就需要使用value
<input id="inputValue" type="text"/>
document.getElementById('inputValue').value
