[英]How do I make text bold after the user clicks a button?
I am trying to make a text editor in JavaScript and it has various features like bolding the text and italics and some others.我正在尝试用 JavaScript 制作一个文本编辑器,它具有各种功能,例如加粗文本和斜体以及其他一些功能。 When the user clicks on any one of them, then anything that they have selected will become edited accordingly.
当用户点击其中任何一个时,他们选择的任何内容都将相应地进行编辑。 Now I am able to get the selected text and even put strong tags before and after the text but when I do it the text doesn't get bold only the tags are seen.
现在我能够获取选定的文本,甚至在文本之前和之后放置强标签,但是当我这样做时,文本不会变粗,只会看到标签。 How can make the text bold?
如何使文本加粗? I sorry but I am unable to provide code since its too much and too messy.
对不起,我无法提供代码,因为它太多太乱了。 Thanks for reading query!
感谢阅读查询! Also if you know any JavaScript library which could help me solve this problem then you can suggest me.
另外,如果您知道任何可以帮助我解决此问题的 JavaScript 库,那么您可以向我推荐。
document.getElementById("button").addEventListener("click", () => { let text = document.getElementById("text").innerText let selection = window.getSelection(); let boldText = "<strong>" + selection + "</strong>" document.getElementById("text").innerText = text.replace(selection, boldText) })
<div id="text"> The dog barks and runs around. </div> <button id="button">Make selected text bold</button>
I am using inner text instead of inner html in order to reproduce the problem我正在使用内部文本而不是内部 html 来重现问题
You are using innerText
to replace which is wrong as we want to change html so use innerHTML
.您正在使用
innerText
替换哪个是错误的,因为我们要更改 html 所以使用innerHTML
。 Code:代码:
document.getElementById("button").addEventListener("click", () => { let text = document.getElementById("text").innerText let selection = window.getSelection(); let boldText = "<b>" + selection + "</b>" document.getElementById("text").innerHTML = text.replace(selection, boldText) //use innerhtml instead of innertext })
<div id="text"> The dog barks and runs around. </div> <button id="button">Make selected text bold</button>
Here is some code that I used to change to inputted text on a button click这是我用来在单击按钮时更改为输入文本的一些代码
<input type="text" id="sign" value="">
<p style = "font-family: 'Dancing Script', cursive; font-size:50px;"
id="signOutput"></p>
<button onclick="signFunction()">Output Signature</button>
<script>
function signFunction() {var x = document.getElementById("sign").value;
document.getElementById("signOutput").innerHTML = x;
}
</script>
<p id="mypar">Hello</p>
<br>
<button type="button" onclick="changeStyle()">Click Me</button>
<script>
function changeStyle(){
var element = document.input
var element = document.getElementById("mypar");
element.style.fontWeight = "bold";
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.