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>