简体   繁体   中英

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)

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.
  • 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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