javascript - textarea中活动线的线条颜色
问题描述
是否可以使用背景颜色突出显示文本区域中的当前行?
例子:
textarea {
resize: none;
background-color: #202020;
line-height: 20px;
color: #FFFFFF;
height: 1200px;
width: 1000px;
}
<textarea spellcheck="false">
test
test
test
test
test
test
test
test
</textarea>
解决方案
在 textarea 元素中格式化文本是非常棘手的。
这个片段的方向略有不同,它在 textarea 后面放置一个 div 并在每个 keyup(并单击)上找到插入符号的位置(选择的开始)并将字符从 textarea 复制到 div 直到该点,替换<br>
换行符(十进制值 10)字符。
当添加行或 CSS 决定它需要进行换行时,div 的高度会扩展。div 有一个背景图像,它是从底部开始的 20px 红色的线性渐变,这意味着它的最后一行被突出显示,并且随着内容被删除/添加到 textarea 中,它会上下移动。
function keyupnclick() {
highlight.innerHTML = '';
let x = textarea.selectionStart;
let str = '';
let i = 0;
for (i; i <= x; i++) {
let ch = textarea.value[i];
let chcode = textarea.value.charCodeAt(i);
if (chcode == 10) {
ch = '<br>';
}
str = str + ch;
}
highlight.innerHTML = str;
}
const textarea = document.querySelector('textarea');
const highlight = document.querySelector('.highlight');
textarea.addEventListener('keyup', keyupnclick);
textarea.addEventListener('click', keyupnclick);
.container {
background-color: #202020;
width: 1000px;
position: relative;
}
.highlight,
textarea {
/* ensure the highlighted div and the textarea have the same izing styles */
font-family: 'arial', sans-serif;
font-size: 16px;
line-height: 20px;
width: 1000px;
}
.highlight {
position: absolute;
height: auto;
background-image: linear-gradient(to top, red 0, red 20px, transparent 20px, transparent 100%);
color: transparent;
}
textarea {
resize: none;
background-color: transparent;
color: #FFFFFF;
height: 1200px;
position: relative;
}
<div class="container">
<div class="highlight"></div>
<textarea spellcheck="false">
test
test
test
test
test
test
test
test
test
</textarea>
</div>
注意:高亮 div 和 textarea 位于与 textarea 相同尺寸的 div 内,以便获得背景灰色。
推荐阅读
- java - 尝试生成签名的 APK 时出现 TaskExecutionException
- sql - 在 SQL 中实现 LIMIT 的其他替代方法
- python - pandas 将 ylabels 绘制到右侧或从右到左绘制负值
- android - Gson 如何将 Json 放入具有随机属性的 Pojo
- python - 通过复制并粘贴到 Anaconda 的目录来安装包
- angular - 如何在 angular5 组件中设置 TinyMCE-Angular 初始化配置而不是 HTML?
- android - HorizontalScrollView 正在崩溃 onRestoreInstance
- ms-access - Ms-Access - IF 复选框 = true THEN
- python-3.x - python-3:如何创建一个新的 pandas 列作为另一列的两个连续行的减法?
- wordpress - 如何在表单字段中将 woocommerce 产品类别作为下拉列表?我正在使用船长表单插件来构建自定义表单