1.window.getSelection/document.getSelection:返回一個Selection對象,表示用戶選擇的文本範圍或光標的當前位置。
2.window.getSelection().getRangeAt(index)/document.getSelection().getRangeAt(index):返回一個包含當前選區內容的區域對象。
3.window.getSelection().getRangeAt(index).deleteContents()/document.getSelection().getRangeAt(index).deleteContents():刪除文檔的區域
4.window.getSelection().getRangeAt(index).insertNode(newNode)/document.getSelection().getRangeAt(index).insertNode(newNode):在範圍的開頭插入一個節點。
5.contenteditable:在HTML中,讓不可編輯的元素可以編輯
添加超鏈接demo
<template>
<div class="hello">
<el-button type="primary" @click="flag && addLink()"><span ref="btn" style="color: gray">添加超鏈接</span></el-button>
<div class="msgContent" ref="msgContent" placeholder="輸入信息內容" contenteditable @mouseup="handleLink" @blur="handleChangBlur"></div>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
flag: false, // 是否可以打開添加超鏈接的方法
linkword: '', // 需要加連接的文字
rangeObj: '' // 選區對象
}
},
methods: {
// 添加鏈接
addLink() {
console.log('xxx')
this.$prompt('請輸入郵箱', '提示', {
confirmButtonText: '確定',
cancelButtonText: '取消',
inputPattern: /^((ht|f)tps?):\/\/[\w\-]+(\.[\w\-]+)+([\w\-.,@?^=%&:\/~+#]*[\w\-@?^=%&\/~+#])?$/,
inputErrorMessage: 'url不合法'
}).then(({ value }) => {
this.rangeObj.deleteContents(); // 刪除這個選中的選區對象,因爲後面會手動創建一項新的內容,解決後面多一項
let box = document.createElement('a');
box.setAttribute('href',value);
box.setAttribute('contenteditable', false);
box.setAttribute('target','_blank');
box.style.color = 'rgb(25, 137, 250)';
box.innerText = this.linkword;
this.rangeObj.insertNode(box);
this.$refs.btn.style.color = 'gray';
this.flag = false;
}).catch(() => {
this.$message({
type: 'info',
message: '取消輸入'
});
this.$refs.btn.style.color = 'gray';
this.flag = false
});
},
// 爲選中的字段綁定超鏈接
handleLink() {
let msgContent = this.$refs.msgContent.innerText;
if(msgContent.length !== 0) { // 富文本有內容輸入
this.linkword = this.mouse_select_Text().toString(); // 得到鼠標獲得文本轉字符串
if(this.linkword.length === 0) { // 如果沒用選中文本,此時阻止添加超鏈接方法
this.flag = false;
} else {
this.flag = true;
this.$refs.btn.style.color = 'white';
this.rangeObj = this.mouse_select_Text().getRangeAt(0); // 獲得選區對象
}
}
},
// 獲得鼠標選中的文本
mouse_select_Text() {
if (window.getSelection) {
return window.getSelection();
} else if (document.getSelection) {
return document.getSelection()
} else {
return '';
}
},
handleChangBlur() {
console.log('blur')
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.hello {
width: 1200px;
margin: 0 auto;
}
.msgContent {
margin: 0 auto;
line-height: 20px;
font-family: '微軟雅黑';
color: #606266;
height: 160px;
width: 300px;
max-height: 160px;
border: 1px solid #DCDFE6;
border-radius: 5px;
overflow-y: auto;
padding: 5px 15px;
outline: none;
font-weight: 400;
font-size: 14px;
}
.msgContent:focus {
border-color: #409EFF;
}
.msgContent:empty::before {
content: attr(placeholder);
font-family: '微軟雅黑';
color: #C0C4CC;
}
.msgContent:focus::before {
content: none;
}
</style>