如何在特定的div中获取getSelection()? [英] How to getSelection() within a specific div?

查看:167
本文介绍了如何在特定的div中获取getSelection()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个内容可编辑的div(标识为"editor1"),允许用户输入文本.然后有一个功能,使他们可以为任何突出显示的文本着色.我的js使用 window.getSelection().getRangeAt(0),但是这样做的问题是它们可以突出显示div之外的单词,并且它们的颜色也会改变.迄今为止;我尝试过:

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);
    }
    }

提琴: https://jsfiddle.net/xacqzhvq/

如您所见,如果我突出显示这也将变成红色",我也可以使用按钮将其设置为红色.如何仅在editor1 div中仅对突出显示的文本进行着色?

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?

推荐答案

您可以使用 .baseNode 从选择中获取节点元素.从那里可以获取父节点,并将其用于比较.

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

在下面的示例中,我使 div 具有一个 id ,您可以检查以确保它是该元素:

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

演示

@ z0mBi3 所述,这将在第一次使用.但是对于许多高亮部分(如果碰巧被清除)可能不起作用. div 中的&span> 元素创建一个层次结构,其中 div 是许多 span 的父元素元素.解决方案是遍历该节点的祖先,直到找到ID为"foo" 的ID.

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

幸运的是,您可以使用 jQuery 通过其

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;

这是的本机JS实现方法的答案.最接近的() .

这篇关于如何在特定的div中获取getSelection()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆