Textarea实现左侧显示行号,右侧编辑内容,类似json编辑器。
1、html内容
<!-- 多行文本框编译器 -->
<div class="edit-container">
<div class="edit">
<div class="leftBox">
<textarea
wrap="off"
cols="2"
id="leftNum"
disabled
></textarea>
</div>
<textarea
v-model="areaText"
@input="handleTextareaInput"
onscroll="document.getElementById('leftNum').scrollTop = this.scrollTop;"
spellcheck="false"
class="area-content"
></textarea>
</div>
</div>``
2、js(使用的vue3+ts,其他版本可自行转换)
setup(){
const areaText = ref('\n');
const num = ref('');
function handleTextareaInput(e) {
let str = '';
if (e.target) {
str = e.target.value;
} else {
str = e;
}
str = str.replace(/\r/gi, '');
str = str.split('\n');
let n = str.length;
let lineobj = document.getElementById('leftNum');
for (let i = 1; i <= n; i++) {
if (document.all) {
num.value += i + '\r\n'; //判断浏览器是否是IE
} else {
num.value += i + '\n';
}
}
lineobj.value = num.value;
num.value = '';
}
return {
areaText,
num,
handleTextareaInput
};
}
3、css代码块
<style lang="less" scoped>
.edit-container {
height: 400px;
padding: 10px 20px;
}
.edit {
display: flex;
height: 380px;
}
.leftBox {
width: 40px;
height: 100%;
text-align: left;
}
.area-content {
padding: 10px 8px;
width: 100%;
height: 100%;
font-size: 13px;
line-height: 24px;
color: 373737;
font-family: Consolas;
border: none;
background: #f5f5f5;
box-sizing: border-box;
outline: none;
resize: none;
}
#leftNum {
padding: 10px 4px;
height: 100%;
width: 100%;
line-height: 24px;
font-size: 13px;
text-align: right;
color: #fff;
font-weight: bold;
resize: none;
outline: none;
// overflow-y: hidden;
// overflow-x: hidden;
border: 0;
background: #6666;
box-sizing: border-box;
overflow: hidden;
}
</style>