如何为每个文本区域行指定不同的样式



我需要一个文本区域,可以为每一行设置不同的背景色,我已经使用了::一线伪元素,但我如何更改另一行的样式?

#field{
height: 100px;
width: 200px;
}
#field::first-line{
background-color: #f33;
}
<textarea id='field'>
I want this to be red.
This to be green.
This to be blue and keep the same if there is not enough space.
And this another color.
</textarea>

文本区域不能是"块";容器,您无法用CSS模拟这种行为。

我使用了与文本区域风格相同的div作为背景,但为文本区域背景添加了透明度。通过这种方式可以看到添加到背景中的样式。

backdropInput()
backdropScroll()
function backdropInput(){
backdropStyle();
backdrop.innerHTML = "";
let colors = ['#f33', '#3f3', '#66f'];
let i = 0
for(section of field.value.split("n")){
backdrop.innerHTML += "<span style='background-color: "+colors[i]+"'>"+section+"</span><br>"
i < colors.length-1 ? i++ : i = 0
}
}
function backdropScroll(){
backdrop.scrollTop = field.scrollTop;
}
function backdropStyle(){
let css = window.getComputedStyle(field);
let cssstring = "";
for (let i = 0; i < css.length; i++) {
cssstring +=(css[i] +': '+css.getPropertyValue(css[i])+";");
}
backdrop.style = cssstring;
backdrop.style.position = 'absolute';
backdrop.style.zIndex = '-1'
backdrop.style.overflow = 'hidden';
backdrop.style.backgroundColor = '#fff';
backdrop.style.fontColor ='#f00';
backdrop.style.resize = 'none';
}
//=================================================================================
//=================================================================================
//textarea resize
document.getElementById("field").addEventListener("mousedown", function(){
backdrop.style.display = 'none'
})
document.getElementById("field").addEventListener("mouseup", function(){
backdropStyle();
});
#field{
height: 200px;
width: 200px;
background-color: rgba(0, 0, 0, 0);
}
<div id="backdrop"></div>
<textarea id='field' oninput="backdropInput()" onscroll="backdropScroll()">
This is red.
This is green.
This is blue and keep the same if there is not enough space.
This is red.
This is green.
This is blue and keep the same if there is not enough space.
And the colors keep looping
</textarea>

最新更新