|
|

楼主 |
发表于 2024-7-3 20:36
|
显示全部楼层
本帖最后由 马黑黑 于 2024-7-3 22:40 编辑
为便于学习、研究,公布一楼源码如下:
- <style>
- #hE { width: 800px; min-height: 400px; font: normal 16px/20px Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace; -webkit-user-modify: read-write-plaintext-only; border: 1px solid gray; pre-wrap; word-break: break-word; overflow-x: hidden; overflow-y: auto; tab-size: 4; padding: 10px; margin: 10px auto; position: relative; }
- #hE:empty::before { position: absolute; content: attr(data-placeholder); color: gray; }
- .tMid { text-align: center; padding: 10px; }
- ::highlight(he-red) { color: red; }
- ::highlight(he-green) { color: green; }
- ::highlight(he-blue) { color: blue; }
- ::highlight(he-magenta) { color: magenta; }
- ::highlight(he-darkred) { color: darkred; }
- </style>
- <div id="hE" data-placeholder="请输入CSS代码"></div>
- <p class="tMid"><button id="btnTest" type="button" value="test">着色效果重置</button></p>
- <script>
- (function() {
- if(!CSS.highlights) {
- hE.dataset.placeholder = '您的浏览器不支持CSS高亮伪元素';
- return;
- }
- //着色匹配正则
- const regRed = /[@.#:]{1,}\w+-?\w+\b|[0-9]+|\w+=/g;
- const regGreen = /\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*|<!--[\s\S]*?-->$/g;
- const regBlue = /[\w-]+\s?:/g;
- const regMagenta = /(["'])((?:\\\1|(?:(?!\1)).)*)(\1)/g;
- const regDarkRed = /<.+?>/g;
- var hls = [], regs = []; //高亮颜色数组&正则匹配数组
- //高亮颜色与匹配对象
- let heColors = {
- blue: regBlue,
- red: regRed,
- magenta: regMagenta,
- green: regGreen,
- darkred: regDarkRed,
- };
- //注册高亮
- const setHighlight = () => {
- hls.length = regs.length = 0;
- Object.keys(heColors).forEach(key => {
- const hlColor = new Highlight();
- hls.push(hlColor); //color
- regs.push(heColors[key]); //regix
- CSS.highlights.set(`he-${key}`, hlColor);
- });
- };
- //着色
- const hlight = (ele) => {
- if(CSS.highlights.size === 0) setHighlight();
- //console.log(CSS.highlights.size);//测试
- const walker = document.createTreeWalker(hE, NodeFilter.SHOW_TEXT);
- while(walker.nextNode()) {
- let textNode = walker.currentNode;
- let text = textNode.textContent;
- regs.forEach((reg,rkey) => {
- let res = text.matchAll(reg);
- res.forEach(r => {
- const range = new Range();
- range.setStart(textNode, r['index']);
- range.setEnd(textNode, r['index'] + r[0].length);
- hls[rkey].add(range);
- });
- });
- }
- };
- hE.oninput = () => hlight(hE);
- //Tab键输入
- hE.onkeydown = (e) => {
- if(e.keyCode !== 9) return;
- e.preventDefault();
- var sel = document.getSelection(),
- range = sel.getRangeAt(0),
- tabNode = document.createTextNode('\t');
- range.insertNode(tabNode);
- range.setStartAfter(tabNode);
- range.setEndAfter(tabNode);
- };
- //着色效果重置
- btnTest.onclick = () => {
- CSS.highlights.clear();
- hlight(hE);
- hE.focus();
- };
- })();
- </script>
复制代码
|
评分
-
| 参与人数 1 | 威望 +50 |
金钱 +100 |
经验 +50 |
收起
理由
|
红影
| + 50 |
+ 100 |
+ 50 |
赞一个! |
查看全部评分
|