How to getSelection() within a specific div?

本小妞迷上赌 提交于 2021-02-18 12:46:15

问题


I have a contenteditable div (with id 'editor1') that allows users to input text. There is then a function that allows them to color any highlighted text. My js uses window.getSelection().getRangeAt(0), but the issue with this is that they can highlight words outside of the div and their color will change as well. So far; I've tried:

        function red(){
    {       
        var getText = document.getElementById("editor1").innerHTML;
        var selection = getText.getSelection().getRangeAt(0);
        var selectedText = selection.extractContents();
        var span = document.createElement("span");
        span.style.color = "red";
        span.appendChild(selectedText);
        selection.insertNode(span);
    }
    }

Fiddle: https://jsfiddle.net/xacqzhvq/

As you can see, if I highlight "this will become red as well", I can use the button to make that red too. How can I only color the highlighted text only within the editor1 div?


回答1:


You are able to get the node element from the selection using .baseNode. From there you can get the parent node and use that for comparison.

function red(){
    // If it's not the element with an id of "foo" stop the function and return
    if(window.getSelection().baseNode.parentNode.id != "foo") return;
    ...
    // Highlight if it is our div.
}

In the example below I made the div have an id that you can check to make sure it's that element:

Demo


As @z0mBi3 noted, this will work the first time. But may not work for many highlights (if they happen to get cleared). The <span> elements inside the div create a hierarchy where the div is the parent elements of many span elements. The solution to this would be to take traverse up through the ancestors of the node until you find one with the id of "foo".

Luckily you can use jQuery to do that for you by using their .closest() method:

if($(window.getSelection().baseNode).closest("#foo").attr("id") != "foo") return;

Here is an answer with a native JS implemented method of .closest().




回答2:


Are you looking for this,

  //html
  <body>
     <p id='editor1'>asdf</p>
     <button onclick='red()'>
     RED
     </button>
  </body>

  //JavaScript

    window.red = function(){
        //var getText = document.getElementById("editor1").innerHTML;
        var selection = window.getSelection().getRangeAt(0);
        var selectedText = selection.extractContents();
        var span = document.createElement("span");
        span.style.color = "red";
        span.appendChild(selectedText);
        selection.insertNode(span);
    }

Plunker: https://plnkr.co/edit/FSFBADoh83Pp93z1JI3g?p=preview



来源:https://stackoverflow.com/questions/38758713/how-to-getselection-within-a-specific-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!