简体   繁体   English

我想使用 window.getSelection 制作一个具有粗体功能的 HTML 文本编辑器

[英]I want to make a HTML text editor having bold functionality using window.getSelection

It makes the whole text bold.它使整个文本加粗。 I want only selected text to get bold (Strictly no exec Command)我只希望选定的文本变粗(严格没有 exec 命令)

let boldBtn = document.getElementById('Bold-Btn');
let boldClickListener = (event) =>
{
    event.preventDefault();
    let selection = window.getSelection();
    let final = `<span class="text-bold">${selection.focusNode.textContent}</span>`;
    selection.anchorNode.parentElement.innerHTML=final;
    console.log(selection);
};

boldBtn.addEventListener('click',boldClickListener);

One way of doing this might be to do the following:这样做的一种方法可能是执行以下操作:

  • Get the window selection.获取 window 选择。
  • Convert the selection to a string to get the text.将选择转换为字符串以获取文本。
  • Create the element that will be bold.创建将是粗体的元素。
  • Replace the selected text contained in the innerHTML of the parentElement with the bolded element.parentElementinnerHTML中包含的选定文本替换为粗体元素。

Example based on the code you provided:基于您提供的代码的示例:

 let boldBtn = document.getElementById('Bold-Btn'); let boldClickListener = (event) => { event.preventDefault(); // Get selection let selection = window.getSelection(); // Get string of text from selection let text = selection.toString(); // Create bolded element that will replace the selected text let final = `<span class="text-bold">${text}</span>`; // Replace the selected text with the bolded element selection.anchorNode.parentElement.innerHTML = selection.anchorNode.parentElement.innerHTML.replace(text, final); }; boldBtn.addEventListener('click', boldClickListener);
 .text-bold { font-weight: bold; }
 <div> Test this text </div> <button id="Bold-Btn"> Bold </button>

Note that you may want to add some more logic when creating your bold element to handle if any existing text is already bold.请注意,您可能希望在创建粗体元素时添加更多逻辑,以处理任何现有文本已经是粗体的情况。

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

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