【问题标题】:how to get selected text range and add color to the particular selected text如何获取选定的文本范围并为特定的选定文本添加颜色
【发布时间】:2017-02-08 12:53:17
【问题描述】:

我遇到了一个问题,我有这样的描述性原始文本 -

<p>I am using the following code to change the color of text but it is not working.. Can anyone help me with this? the soloution in javascript or jquery anything is fine..</p> 

现在我的要求是

  • 在鼠标向上事件中查找特定选定文本的位置(范围)
  • 在整个操作过程中为选定的文本着色

我写的代码

    $(document).ready(function() {
            if (!window.Wafer) {
                Wafer = {};
            }
            Wafer.Selector = {};

            /* Function to get selected string as a object
             *  works for all browser and also handle for old browser like
             * ie9,firfox 18 as discussed
             */
            Wafer.Selector.getSelected = function() {

                $selObj = '';
                if (window.getSelection) {
                    $selObj = window.getSelection();
                } else if (document.getSelection) {
                    $selObj = document.getSelection();
                } else if (document.selection) {
                    $selObj = document.selection.createRange().text;
                }
                //console.log($selObj);
                return $selObj;
            }
            //holding the selector string in variable on mouseup event
            Wafer.Selector.mouseup = function() {
                $selector = Wafer.Selector.getSelected();
                $start = $selector.anchorOffset;
                $end = $selector.focusOffset;
                console.log($start, $end);
                //I call this to wrap selected text under span 
                selectText('#f90');
            }
            //This will tell jquery to fire when "mouseup" event will occur
            $(document).on("mouseup", Wafer.Selector.mouseup);
        });

        function selectText(hexColor) {
            var selection = window.getSelection().getRangeAt(0);
            var selectedText = selection.extractContents();
            var span = document.createElement('span');
            span.style.backgroundColor = hexColor;
            span.className = 'selected-text';
            span.appendChild(selectedText);
            selection.insertNode(span);
        }

在函数 selectText 中我曾经得到 window.getSelection().getRangeAt(0); 可能与 window.getSelection() 冲突> 并且两者都返回具有 anchoroffsetfocusoffset 键的对象,因此无法获得正确的文本范围

有什么方法可以清除选中的文本范围吗?

关注了几个堆栈帖子,例如this,但这些帖子部分满足了我的要求并且代码有问题。 提前致谢。

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    有这个问题的人可以通过这种方式获得帮助-

    $("#text-box").mouseup(function () {
        var el = document.getElementById("text-box");
        getCaretCharacterOffsetWithin(el);
    });
    

    每次都从父容器获取选择和查找开始和结束范围的功能。

     function getCaretCharacterOffsetWithin(element) {
        var caretOffset = 0;
        var doc = element.ownerDocument || element.document;
        var win = doc.defaultView || doc.parentWindow;
        var sel;
        if (typeof win.getSelection != "undefined") {
            sel = win.getSelection();
            if (sel.rangeCount > 0) {
                var range = win.getSelection().getRangeAt(0);
                var preCaretRange = range.cloneRange();
                preCaretRange.selectNodeContents(element);
                preCaretRange.setEnd(range.endContainer, range.endOffset);
                caretOffset = preCaretRange.toString().length;
            }
        } else if ((sel = doc.selection) && sel.type != "Control") {
            var textRange = sel.createRange();
            var preCaretTextRange = doc.body.createTextRange();
            preCaretTextRange.moveToElementText(element);
            preCaretTextRange.setEndPoint("EndToEnd", textRange);
            caretOffset = preCaretTextRange.text.length;
        }
        var start = caretOffset - sel.toString().length;
        var end = caretOffset - 1;
        if (start != end && end > start) {
            // Highlight the text
            console.log(start,end);
            var selectedText = range.extractContents();
            var text_value = selectedText.textContent;
            var span = document.createElement('span');
            span.style.backgroundColor = "red";
            span.className = 'selected-text';
            span.appendChild(selectedText);
            range.insertNode(span);
            $(".span").html(start + ",&nbsp;" + end);
            return caretOffset;
        }
    }
    

    您的 HTML 可能是这样的

    <div id="text-box" style="width: 700px; border:1px solid black">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum</div>
    

    我还添加了 span 标签来包装在 mouseup 事件中选择的范围文本,因为我需要 添加颜色 到被选中的字段。希望这会有所帮助。 :-)

    【讨论】:

      【解决方案2】:

      更新

      为特定文本添加颜色

      $(".my").hrStringColor({
              string      : "Hi i am Hidayt Rahman. You can add your own", //optional
              charFrom    : 5,  // Index of character, where to start
              charTo      : 25, // Index of character, where to end
              color       : "green" // add your color
      });
      

      可能对你有帮助,去那里-> hrStringColor

      【讨论】:

      • 现在只有结束字符范围
      • 更新了,可以在字符串的任意位置选择应用颜色
      猜你喜欢
      • 1970-01-01
      • 2012-08-25
      • 2013-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-22
      相关资源
      最近更新 更多