简体   繁体   中英

Javascript making text bold?

I am trying to use javascript to make text bold. I have searched the net and it seems that I can do a document.write() after I made my string bold. Isn't there any way to perform this without opening any new page (in the same html text area)?

function bold()
{
   document.write(selectedText.bold());
}

Edit: I am implementing an Text Editor and I am using a HTML TextArea, and I am trying to add all the functionality such as bold, italic, etc. I want to be able to select part of the text written and make it bold.

// method 1: direct write out something with bold tags
document.write('<b>My Bold Text</b>');

// method 2: add an element styled to be bold
var span = document.createElement('span');
span.innerHTML = 'My Bold Text';
span.style.fontWeight = 'bold';
document.getElementsByTagName('body')[0].appendChild(span);

// method 3: add an element classed to be bold
// add style sheet first:
//   <style type="text/css">.bold { font-weight: bold; }</style>
// then the jS:
var span = document.createElement('span');
span.innerHTML = 'createElement.className - My Bold Text';
span.className = 'bold';
document.getElementsByTagName('body')[0].appendChild(span);

Something like that? Otherwise, please be more specific with your question.

Do you want to set an existing element to bold? If this is the case, set font-width CSS property to bold . Try this:

document.getElementById("myTextId").style.fontWeight = "bold";

or, if you are using jQuery,

$('#myTextId').css("font-weight", "bold");

Update: HTML <textarea> tag does not support separate styling of different parts of its content; you can't make a rich text editor this way.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM