繁体   English   中英

使用JavaScript更改突出显示的文本的字体

[英]Change font on highlighted text using JavaScript

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

<!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>

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

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

 <!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> 

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

  • 颜色
  • 背景颜色
  • 光标
  • 脱字色
  • 大纲及其长手
  • 文本修饰及其相关属性
  • 文本强调色
  • 文字阴影

 #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> 

暂无
暂无

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

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