效果圖展示:

這是一個比較簡易的文本編輯框顯示,此文主要講文本編輯相關~
文本編輯實現原理分析:
- 一般涉及到文本編輯,我們通常會使用 input 輸入框來實現,但是像一些需要含有特殊樣式標題的文本編譯框,input 顯然滿足不了我們的需求,這時候我們需要用到一個可以使任何元素都可以具有編輯功能的屬性: contenteditable 只需要在元素上設置contenteditable="true",該元素即可進行編輯
- 默認進入該頁面時,文本框聚焦,通過 directives 設置 自定義指令
- 編輯的文本要默認設置好相關標題長度的距離,不然會和標題重疊在一起, 可以通過 text-indent 這個設置首行縮進距離的屬性解決,由於標題是動態獲取的數據,所以設置時不能寫死,所以要根據標題長度進行設置
- 編輯好的內容 通過 input事件去獲取
以上就是js實現帶有不同樣式標題的文本編輯方式重要點
核心代碼
html:
<template>
<div class="nineImgs_wrap">
<div class="edit_container">
<span class="title">#{{title}}#</span>
<div
class="edit_box"
contenteditable="true"
v-html="message"
ref="editBox"
id="editBox"
@input="changeText"
v-focus
:style="{'text-indent':indentNumber + 'em'}"
></div>
</div>
</div>
</template>
js:
data() { return { title: "你對后浪的感觸", message: '片中說:科技繁榮,文化繁茂,城市繁華,現代文明的成果被層層打開,可以盡情享用。我要說,那個追着無人機幾條街的孩子,那些高中入學率只有一半的學生,那些996的職員,那些被房價壓得喘不過氣的年輕人,這也是青年,這也是我們的生活。現代文明的成果並沒有傳遞到每個人,現代社會的結構性矛盾卻無時不刻不成為着重壓在每個人頭頂的利劍。', indentNumber: 0, }; }, directives: { focus: { // 指令的定義 inserted: function (el) { el.focus() } } }, created() { this.indentNumber = this.title.length + 4.5 }, methods: { changeText(){ this.commentInner = this.$refs.editBox.innerHTML console.log(this.commentInner); }, }
css:
<style lang="less" scoped> .nineImgs_wrap { width: 100%; padding: 30px; font-size: 18px; .edit_container { width: 100%; position: relative; margin-bottom: 40px; .title { color: #1a7bd7; margin-right: 7px; position: absolute; left: 0; } .edit_box { border: 0; width: 100%; height: 100%; // background: rgba(0, 0, 0, 0.2); outline: none; min-height: 200px; margin-bottom: 20px; color: #000000; text-align: left; } } } </style>
* contenteditable
兼容性很好,兼容所有主流瀏覽器。
用法很簡單,只需要給你需要的標簽填上即可。
該屬性可繼承,只要父元素設置后,子元素也可進行編輯
<div contenteditable="true">我是一個div</div>
分享一刻:
