gpt4 book ai didi

javascript - 将文本区域中的少量文本更改为粗体

转载 作者:行者123 更新时间:2023-11-27 23:04:52 25 4
gpt4 key购买 nike

假设我有这段文字

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

我要大胆

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

如果我要在 Javascript 中执行此操作

function myFunction(obj) {
var text1 = "Lorem ipsum ";
var text2 = "dolor sit amet";
var text3 = ", consectetur adipiscing elit.";
text2.bold();

obj.value = text1 + text2 + text3;
}
<textArea onmouseup=myFunction(this)>Lorem ipsum dolor sit amet, consectetur adipiscing elit</textArea>

我似乎无法将文本加粗,有什么想法吗?

最佳答案

因为您不能在 textarea 中设置文本样式,
下面是一个使用内容可编辑的 div 的解决方案:
(灵感来 self 对另一个问题的解决方案:Change font for selected text using JavaScript)

function changeStyle(style) {
var sel = window.getSelection(); // Gets selection
if (sel.rangeCount) {
// Creates a new element, and insert the selected text with the chosen style
var e = document.createElement('span');
e.classList.add(style.value); // Selected style (class)
e.innerHTML = sel.toString(); // Selected text

// https://developer.mozilla.org/en-US/docs/Web/API/Selection/getRangeAt
var range = sel.getRangeAt(0);
range.deleteContents(); // Deletes selected text…
range.insertNode(e); // … and inserts the new element at its place
}
}
.editable {
width: 360px;
height: 120px;
border: 1px solid #ccc
}

.editable .span-0{ /* Added to reset styles correctly */
font-weight: normal; /* Reset b */
text-decoration: none; /* Reset u */
font-style: normal; /* Reset i */
}

.editable .span-b{
font-weight: bold;
}

.editable .span-u{
text-decoration: underline;
}

.editable .span-i{
font-style: italic;
}
Highlight text and change style<br>
<select id="select_font" onchange="changeStyle(this);">
<option value="span-0" selected>None</option>
<option value="span-b">Bold</option>
<option value="span-u">Underlined</option>
<option value="span-i">Italic</option>
</select>
<div contenteditable="true" class="editable">
Some Content
</div>

(我添加了其他样式选项……只是因为!)

希望对您有所帮助!

关于javascript - 将文本区域中的少量文本更改为粗体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50286692/

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