简体   繁体   English

Javascript使文本加粗?

[英]Javascript making text bold?

I am trying to use javascript to make text bold. 我正在尝试使用javascript使文本加粗。 I have searched the net and it seems that I can do a document.write() after I made my string bold. 我搜索了网络,并且在将字符串加粗后,似乎可以执行document.write()了。 Isn't there any way to perform this without opening any new page (in the same html text area)? 没有任何方法可以执行此操作而不打开任何新页面(在同一html文本区域中)?

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. 编辑:我正在实现一个文本编辑器,并且正在使用HTML TextArea,并且试图添加所有功能,例如粗体,斜体等。我希望能够选择部分文字并将其设为粗体。

// 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 . 在这种情况下,请将font-width CSS属性设置为bold Try this: 尝试这个:

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

or, if you are using jQuery, 或者,如果您使用的是jQuery,

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

Update: HTML <textarea> tag does not support separate styling of different parts of its content; 更新:HTML <textarea>标记不支持其内容不同部分的单独样式; you can't make a rich text editor this way. 您无法以这种方式制作富文本编辑器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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