<分区>
标签 javascript html css text
我想知道是否可以使用 JavaScript 和 CSS 为任何长度的文本自动着色。例如,如果我在 h1 标签上使用 contentEditable
并且用户通过他们的浏览器编辑它,它将在同一区域返回彩色文本。第一个字母一种颜色,第二个字母另一种,依此类推。不只是一种颜色,而是多种颜色。
是否可以继续使用 7 色图案?
最佳答案
我做了一点proof of concept (JSFiddle) .它基本上获取了 contentEditable = true
的 div 文本,将每个字母包装在一个 span 中并将其放入输入 div 后面的 div 中。然后使用一些 CSS 魔法完成着色。
#input {position: absolute; opacity: 0.0;}
#rainbow {position: absolute; background: #cccccc;}
#rainbow span:nth-child(7n+1) {color: blue;}
#rainbow span:nth-child(7n+2) {color: green;}
#rainbow span:nth-child(7n+3) {color: violet;}
#rainbow span:nth-child(7n+4) {color: yellow;}
#rainbow span:nth-child(7n+5) {color: cyan;}
#rainbow span:nth-child(7n+6) {color: orange;}
#rainbow span:nth-child(7n+7) {color: red;}
这是 JS:
function wrapInSpans(str) {
wrappedStr = "";
for (var i = 0, len = str.length; i < len; i++) {
wrappedStr += "<span>" + str[i] + "</span>";
}
return wrappedStr;
}
function rewrapContent(objSrc, objTarget) {
objTarget.innerHTML = wrapInSpans(objSrc.innerText);
}
input = document.getElementById("input");
input.contentEditable = true;
rainbow = document.getElementById("rainbow");
rainbow.contentEditable = true;
input.addEventListener("input", function() {
rewrapContent(input, rainbow);
}, false);
rewrapContent(input, rainbow);
和 HTML:
<div>
<div id="rainbow"></div>
<div id="input">Lorem ipsum dolor sit amet.</div>
</div>
目前唯一的问题是隐藏的 input-div 的文本光标也是不可见的。抱歉,我不确定如何解决这个问题。
关于javascript - 自动着色文本 | JS CSS HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33984400/