如何在javascript中使选定的文本变为粗体/斜体/下划线?

cos*_*smo 4 html javascript jquery

我正在尝试在一个网页上工作,该网页允许用户为学校项目写自己的笔记,而我的想法是让他们使用按钮以粗体/斜体/下划线表示文字。到目前为止,这些按钮都可以使用,但是它们在文本区域内的所有内容均以粗体/斜体/下划线表示。相反,我希望它以这样一种方式工作,即只有它们突出显示的文本才变为粗体/斜体/下划线。我还想知道如何做到这一点,以便当他们单击加粗按钮时,他们从那时起键入的文本将显示为粗体,而当他们再次单击它时,将从那时起键入的文本将显示出来。正常。

<script type="text/javascript">
function boldText(){
    var target = document.getElementById("TextArea");
    if( target.style.fontWeight == "bolder" ) {
        target.style.fontWeight = "normal";
    } else {
        target.style.fontWeight = "bolder";
    }
}



function italicText(){
    var target = document.getElementById("TextArea");
    if( target.style.fontStyle == "italic" ) {
        target.style.fontStyle = "normal";
    } else {
        target.style.fontStyle = "italic";
    }
}

function underlineText(){
    var target = document.getElementById("TextArea");
    if( target.style.textDecoration == "underline" ) {
        target.style.textDecoration = "none";
    } else {
        target.style.textDecoration = "underline";
    }
}
</script>
Run Code Online (Sandbox Code Playgroud)

zer*_*0ne 6

您可以使用execCommand()。该API用于开发文本编辑器。这3个按钮利用了非常多才多艺execCommand()的写作元素是一个带有属性的普通div contenteditable

SNIPPET

<!DOCTYPE html>
<html>

<head>
  <meta charset='utf-8'>
  <style>
    body {
      font: 400 16px/1.4 'serif';
      }
    #editor1 {
      border: 3px inset grey;
      height: 100px;
      width: 381px;
      margin: 10px auto 0;
     }
    fieldset {
      margin: 2px auto 15px;
      width: 358px;
    }
    button {
      width: 5ex;
      text-align: center;
      padding: 1px 3px;
    }
  </style>
</head>

<body>

  <div id="editor1" contenteditable="true">
     The quick brown fox jumped over the lazy dog.
  </div>
  <fieldset>
    <button class="fontStyle" onclick="document.execCommand('italic',false,null);" title="Italicize Highlighted Text"><i>I</i>
    </button>
    <button class="fontStyle" onclick="document.execCommand( 'bold',false,null);" title="Bold Highlighted Text"><b>B</b>
    </button>
    <button class="fontStyle" onclick="document.execCommand( 'underline',false,null);"><u>U</u>
    </button>
  </fieldset>
Run Code Online (Sandbox Code Playgroud)

  • 注意:根据 Mozilla 文档,目前它已过时 https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand (2认同)