gpt4 book ai didi

javascript - 将所选文本加粗

转载 作者:行者123 更新时间:2023-12-03 08:03:19 27 4
gpt4 key购买 nike

我有一个 HTML5 文件,我正在尝试使用 create-electron-app 制作一个类似 Google Docs 的应用程序。

我有一个用于输入的文本区域标记,并且我正在尝试将用户选择的文本加粗。我的 getSelectedText() 函数正在工作,它返回一个像预期的字符串,但我需要在文本区域内加粗该文本。如果您使用过 Google 文档,您应该明白我的意思。

这是代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Make word documents!</title>
<link rel="stylesheet" href="index.css" />
</head>
<body>
<textarea class="userInput"></textarea>

<input type="button"
value="Bold"
onmousedown="bold()">

<script>

function getSelectedText() {
if (window.getSelection) {
return "" + window.getSelection();
} else if (document.selection && document.selection.type == "Text") {
return document.selection.createRange().text;
}
return "";
}


function bold() {
var userInput = getSelectedText();
// userInput.style.fontWeight = "bold";

// print the type of the userinput variable
console.log(typeof userInput);

}
</script>
</body>
</html>

最佳答案

无法在文本区域内将文本加粗,但是可以在 div 内将文本加粗。

通过将 div 设置为 contentEditable,其行为可以像文本区域一样 -- <div contentEditable></div> .

方便的是,Javascript 有一个内置函数可以将选定的文本加粗,document.execCommand("bold") .

通过使用可编辑的 div 和 Javascript 内置函数,可以创建像 Google Docs 这样可以将所选文本加粗的应用程序。

document.getElementById("bold_button").onclick = function() {
document.execCommand("bold");
}
<div contentEditable id="text">
The World Before the Flood is an oil-on-canvas painting by English artist William Etty, first exhibited in 1828. It depicts a scene from John Milton's Paradise Lost in which Adam sees a vision of the world immediately before the Great Flood. The painting illustrates the stages of courtship as described by Milton: a group of men select wives from a group of dancing women, take their chosen woman from the group, and settle down to married life. Behind them looms an oncoming storm, a symbol of the destruction which the dancers and lovers are about to bring upon themselves. When first exhibited at the 1828 Royal Academy Summer Exhibition, the painting attracted large crowds. Many critics praised it, but others condemned it as crude, tasteless and poorly executed. The painting, currently in the Southampton City Art Gallery, and a preliminary oil sketch for it, now in the York Art Gallery, were exhibited together in a major retrospective of Etty's work in 2011 and 2012
</div>
<button id="bold_button">Bold</button>

关于javascript - 将所选文本加粗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73229296/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com