我有问题的JavaScript脚本颜色的文本.它工作正常,但文本只有颜色,如果你点击面板上,并按下“空间”按钮在PC键盘上.如果你按任何其他键(甚至回车),文本不着色.
的数据
我想该脚本自动激活,只要我打开的html文件,使文本自动着色,只要我打开文件。
在html中,我尝试同时使用onchange
和oninput
函数。而在js文件中,我在创建changeColor()
函数后调用它,目的是在打开文件时自动执行它,但它不起作用。抱歉的问题,但我是新来的。我如何解决它?
index.html
<div id="editor" contenteditable="true" oninput="showPreview();" onchange="changeColor();"><h1>This is a Heading</h1>
<p>This is a paragraph.</p>
</div>
<h3>PREVIEW</h3>
<div class="preview-area">
<iframe id="preview-window"></iframe>
</div>
字符串
style.css
#editor {
width: 400px;
height: 100px;
padding: 10px;
background-color: #444;
color: white;
font-size: 14px;
font-family: monospace;
white-space: pre;
}
.statement {
color: orange;
}
型
JavaScript.js
// CHANGE COLOR TEXT
function changeColor() {
var keywords = ["DIV", "DIV", "H1", "H1", "P", "P", "HELLO", "<", ">", "/"];
// Keyup event
document.querySelector("#editor").addEventListener("keyup", (e) => {
// Space key pressed
if (e.keyCode == 32) {
var newHTML = "";
// Loop through words
str = e.target.innerText;
(chunks = str
.split(new RegExp(keywords.map((w) => `(${w})`).join("|"), "i"))
.filter(Boolean)),
(markup = chunks.reduce((acc, chunk) => {
acc += keywords.includes(chunk.toUpperCase())
? `<span class="statement">${chunk}</span>`
: `<span class='other'>${chunk}</span>`;
return acc;
}, ""));
e.target.innerHTML = markup;
// Set cursor postion to end of text
// document.querySelector('#editor').focus()
var child = e.target.children;
var range = document.createRange();
var sel = window.getSelection();
range.setStart(child[child.length - 1], 1);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
this.focus();
}
})
}
changeColor()
//PREVIEW
function showPreview() {
var editor = document.getElementById("editor").innerText;
// var cssCode =
// "<style>" + document.getElementById("cssCode").value + "</style>";
// var jsCode =
// "<scri" + "pt>" + document.getElementById("jsCode").value + "</scri" + "pt>";
var frame = document.getElementById("preview-window").contentWindow.document;
document.getElementById("preview-window").srcdoc = editor;
frame.open();
//frame.write(htmlCode + cssCode + jsCode);
frame.write(editor);
frame.close();
}
showPreview()
型
1条答案
按热度按时间gopyfrb31#
您可以考虑将
changeColor()
的着色部分重构为另一个函数,并在初始加载时立即在JavaScript中调用它: