使用JavaScript

时间:2018-04-15 16:14:28

标签: javascript html

我想在textarea中突出显示文本时更改字体。下面的函数更改textarea中的整个字体,而不是我想要更改的文本。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>E-commerce Website</title>
        <script>          
            function selectFont() {
                document.getElementById("note_header").style.fontFamily = "cursive";
            }
        </script>
    </head> 
    <body> 
        <select id="select_font" onchange="selectFont()">
            <option>Select a font</option>
            <option>Cursive</option>
        </select>
        <textarea id="note_header">Title</textarea>
    </body>
</html>

2 个答案:

答案 0 :(得分:3)

更改Textarea中的文字字体不起作用,但适用于其他属性,如颜色,光标等。

解决方法是使用内容可编辑<div>。在将样式应用于span的内容后,您可以使用window.getSelection获取所选文本,然后使用<span>换行。如下图所示。

&#13;
&#13;
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>E-commerce Website</title>
    <script>          
        function selectFont() {
            selectedText = window.getSelection().toString();
            NoteHeader  = document.getElementById("note_header");
            EditedText = NoteHeader.innerText.replace(selectedText, 
                             `<span style="font-family: cursive">${selectedText} </span>`);
            NoteHeader.innerHTML = EditedText;
        }
    </script>
</head>

<body>
   Highlight text and change font <br>
    <select id="select_font" onchange="selectFont()">
        <option>Select a font</option>
        <option>Cursive</option>
    </select>
    <div contenteditable="true" id="note_header" 
        style="width:200px; height:200px; border: 1px solid #ccc">
        Some Content
    </div>
</body>

</html>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

没有直接的方法来实现您的目标,但您可以使用CSS伪元素::selection为选定的文本提供一些属性。遗憾的是,font-family无法用此更改,但如果您只想以某种方式突出显示它,您可以更改的属性是:

  • color
  • 背景颜色
  • 光标
  • 脱字符号颜色
  • 大纲及其长篇
  • 文字装饰及其相关属性
  • 文本加重色
  • 文字阴影

#note_header::selection {
  color: red;
  background: #eee;
}
<textarea id="note_header">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.</textarea>