I'd like to make text in <i>
tag not appear italic in a contenteditable div.
However, as you can see in the code snippet below, if I add font-style:normal
to italic style, document.execCommand('italic')
to unitalicize no longer works, as the browser correctly detects that the text is not italic.
Would there be any way to have both unitalic-looking <i>
and a way to unitalicize?
function italicize(){ document.execCommand("italic"); }
i{ font-style:normal; color:red; }
<div contenteditable=true>a<i>b</i>c</div> <button onclick=italicize()>italic</button>
function italicize() { let myDiv = document.querySelector("#myDiv"); myDiv.style.fontStyle.localeCompare("italic") ? myDiv.style.fontStyle = "italic" : myDiv.style.fontStyle = "normal"; }
i { font-style: normal; color: red; }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <div id="myDiv" contenteditable=true>a<i>b</i>c</div> <button onclick="italicize()">italic</button> </body> </html>
Is this what you are looking for? #newToStackOverflow
One way to do this can be by creating a specific style rule that removes the default italic style from all <i>
elements inside a <div>
.
Then, with querySelectorAll
you can target all the <i>
that live inside a <div contenteditable="true">
attribute and make the text italicized by toggling a class:
function italicize() { let contentDivs = document.querySelectorAll('[contenteditable="true"] > i') for (let div of contentDivs) { div.classList.toggle('add-italic'); } }
div > i { font-style: normal; color: red; } .add-italic { font-style: italic; }
<div contenteditable="true">a<i>b</i>c</div> <button onclick="italicize()">italic</button>
More Solutions for this problem.
function unitalicize(){ var element = document.getElementsByTagName("i")[0]; var span = document.createElement("span"); while(element.firstChild){ span.appendChild(element.firstChild); } element.parentElement.replaceChild(span,element) } function italicize(){ var element = document.getElementsByTagName("span")[0]; var i = document.createElement("i"); while(element.firstChild){ i.appendChild(element.firstChild); } element.parentElement.replaceChild(i,element) }
i{ color:red; }
<div contenteditable=true>a<i>b</i>c</div> <button onclick=unitalicize()>unitalicize()</button> <button onclick=italicize()>italicize()</button>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.