我已经创建了 HTML 和 javascript 文件。我使用 fontawesome.com 添加了一个粗体图标,并使用该图标制作了一个按钮。使用 execCommand 我试图在单击按钮后使粗体按钮编辑文本区域中的选定文本。但是代码不起作用。
<html>
<head>
<title>
Editor
</title>
<link rel="stylesheet" href="stylesheet.css">
<script src="script.js"> </script>
<script src="https://kit.fontawesome.com/f7ac85e141.js" crossorigin="anonymous"></script>
</head>
<body>
<header>
<div class="navBar" id="heading-container" contentEditable="true">
<button onclick="execCmd('bold');">
<i class="fas fa-bold"></i>
</button>
</div>
</header>
<textarea id="myTextArea"> Lorem ipsum dolor sit amet, consectetur. </textarea>
</body>
</html>
function execCmd(command) {
let field = document.getElementById('myTextArea');
field.document.execCommand(command, false, null);
}
最佳答案
document.execCommand 在 contenteditable 中使用,而不是在 textarea 中使用,所以:
function execCmd(command) {
let field = document.getElementById('heading-container');
field.document.execCommand(command, false, null);
}
btw execcommand 已过时,因此请尝试使用范围替换它。或者您可以在这种情况下使用纯 dom,就像@Mike Poole 的回答一样。
关于javascript - 如何使用javascript execCommand创建富文本编辑器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58862388/