首页 > 解决方案 > 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>

标签: javascripthtmlcss

解决方案


在 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 内,以便获得背景灰色。


推荐阅读