不改变文档结构实时渲染彩虹字
位置:
首页 >
前端三套件[ 发布时间: 2024.6.16 作者: 马黑 阅读: 211 ]
CSS+JS原生文本高亮API测试
代码:
<style>
#t7 { margin: 20px auto; padding: 10px; width: 800px; height: 400px; font-size: 20px; -webkit-user-modify: read-write-plaintext-only; border: 1px solid lightblue; border-radius: 3px; outline-width: 4px; outline-color: cornflowerblue; }
#h7 { text-align: center; }
</style>
<h2 id="h7">CSS+JS原生文本高亮API测试</h2>
<div id="t7"></div>
<script>
const highlights = [];
const addStyleSheet = () => {
const colors = ['#ad26ad', '#5d0a99','#0000ff',' #07c607', '#b3b308', '#ffa500', '#ff0000'];
const hstr = colors.map((c,k) => `::highlight(rainbow-color-${k+1}) {color: ${c}; text-decoration: underline; }`).join('\n');
var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = hstr;
document.body.appendChild(style);
for (let i = 0; i < 7; i++) {
const colorHighlight = new Highlight();
highlights.push(colorHighlight);
CSS.highlights.set(`rainbow-color-${i + 1}`, colorHighlight);
}
};
const hlight = (ele) => {
const walker = document.createTreeWalker(ele, NodeFilter.SHOW_TEXT);
while(walker.nextNode()) {
let textNode = walker.currentNode;
let text = textNode.textContent;
for(let i = 0; i < text.length; i++) {
const range = new Range();
range.setStart(textNode, i);
range.setEnd(textNode, i + 1);
highlights[(i % 7)].add(range);
}
}
};
if (CSS.highlights) {
t7.textContent = '恭喜恭喜!您的浏览器完美支持CSS Custom Highlight API';
addStyleSheet();
hlight(h7);
hlight(t7);
t7.oninput = () => hlight(t7);
} else {
t7.textContent = '非常遗憾!您的浏览器不支持CSS Custom Highlight API'
}
</script>
前一篇: JS原生animate动画之:编写自己的动画(续篇)
下一篇: 实现原生lrc歌词同步之超级简化版
发表评论:
评论列表 [1条]
#1 | 飞飞 于 2024-6-16 11:31 发布: 测试结果:恭喜恭喜!您的浏览器完美支持CSS Custom Highlight API。。。这么漂亮的彩虹字体呀