【问题标题】:Create multiple selection at the same time when using document.selection in Javascript在 Javascript 中使用 document.selection 时同时创建多个选择
【发布时间】:2014-09-23 04:38:26
【问题描述】:

我知道如何使用 document.selection 进行突出显示。对于example

/* http://jsfiddle.net/4J2dy/ */
$("#content").on('mouseup', function() {
    highlighting();
});
var highlighting = function () {
    var seleted_str = (document.all) ? document.selection.createRange().text : document.getSelection();
    if(seleted_str != "") {
        var stringToBeHighlighted = seleted_str.getRangeAt(0);
        var span = document.createElement("span");
        span.style.cssText = "background-color: #80deea";
        span.className = "MT";
        stringToBeHighlighted.surroundContents(span);
    }
};

但有些事情我不知道如何实现。 假设我同时创建了四个具有相同内容的图层。 我想在控制层上选择一个句子,而其他三层中的所有相同句子也会被选中。(见下图)

选择后,我想弹出一个菜单(我可以这样做),并根据按下的按钮获取 DOM 元素。(见下图)

谁能告诉我如何做到这一点?还是根本做不到?如果有人可以为我解答,我将不胜感激。

【问题讨论】:

    标签: javascript jquery html dom web


    【解决方案1】:

    这是可能的,我很感谢 SO 用户 Tim Down 的输入,因为他对 JS 范围/选择了解很多,但我已经介绍了我的部分解决方案。

    您可以只将startOffset 和endOffset 存储在mouseup 上更新的外部对象中,而不是选择4 层。唯一的副作用是用户的选择只会在他们单击图层按钮时获得span 的颜色。

    优点是您现在可以简单地使用 DOM 文本节点而不是范围/选择(无论如何对我来说更复杂)。 我选择在按钮上查找具有data-layer 属性的图层,并在图层本身上查找相应的id。我通过切片图层中文本节点的文本内容来处理“选定范围”的“附加”,如下所示:

    layer.innerHTML = txt.slice(0, selText.start) 
         + '<span class="MT" style="background-color: #80deea">'
         + txt.slice(selText.start, selText.end) + '</span>'
         + txt.slice(selText.end, txt.length);
    

    查看 in action here。我添加了一个 cleanSelection 函数,因此一次只能选择一个(开始和结束计数器失败,因为选择范围不考虑 HTML 标签,所以你必须摆脱跨度)。

    最后的笔记:

    • 小提琴在不支持getElementsByClassName的浏览器中不起作用
    • 小提琴一次只支持一个选择。
    • fiddle 并没有广泛测试所有条件(例如,第一个孩子的节点类型是否真的是文本节点等。但自己添加并不难)

    整个 JS 代码作为参考(也在 fiddle 中):

    // this object will hold the start & end offsets of selection value
    var selText = false; 
    
    // selText will be updated on mouseup
    document.body.onmouseup = getSelText; 
    
    // on button click, selText will be highlighted
    document.body.onclick = function(e) { 
      var target = e.target || e.srcElement, range, layer, txt;
    
      // only do if it's a layer button & the selection is non-empty
      if (target.getAttribute('data-layer') && selText !== false) {
    
         // first remove previous spans, they break the startOffset & endOffset of the selection range
         cleanSelection();
    
         // get the clicked layer
         layer = document.getElementById(target.getAttribute('data-layer'));
         // this assumes that the first node in the layer is a textNode
         txt = layer.firstChild.nodeValue;
         // let's append the selection container now
         layer.innerHTML = txt.slice(0, selText.start) 
         + '<span class="MT" style="background-color: #80deea">'
         + txt.slice(selText.start, selText.end) + '</span>'
         + txt.slice(selText.end, txt.length);
    
        // ...and empty the 'real selection'
        window.getSelection().collapse(); 
        // log results to console
        console.log('From char ' + selText.start + ' to char ' + selText.end + ', in ' + layer.id);
      }
    
    };
    function getSelText () {
        var seleted_str = (document.all) ? document.selection.createRange().text : document.getSelection(), stringToBeHighlighted;
        if(seleted_str !== "") {
            stringToBeHighlighted = seleted_str.getRangeAt(0);
            selText = {
              start: stringToBeHighlighted.startOffset,
              end: stringToBeHighlighted.endOffset
            };
        } else {
            selText = false;
        }
    }
    function cleanSelection() {
      var getText, mtSpan = document.getElementsByClassName('MT');
      for ( var i = 0; i < mtSpan.length; i++) {
        getText = mtSpan[i].innerHTML;
        mtSpan[i].previousSibling.nodeValue = mtSpan[i].previousSibling.nodeValue + getText + mtSpan[i].nextSibling.nodeValue;
        mtSpan[i].parentNode.removeChild(mtSpan[i].nextSibling);
        mtSpan[i].parentNode.removeChild(mtSpan[i]);
      }
    }
    

    【讨论】:

    • 非常感谢您的回答!还要感谢您的笔记节省了我的测试时间。很好的答案和解释=)
    猜你喜欢
    • 2019-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-23
    相关资源
    最近更新 更多