如何用元素环绕/包围突出显示的文本

如何解决如何用元素环绕/包围突出显示的文本

| 我想将选定的文本包装在具有span的div容器中,可以吗? 用户将选择一个文本并单击一个按钮,单击按钮时,我想用span元素包装该选定的文本。我可以使用
window.getSelection()
获得所选文本,但是如何知道其在DOM结构中的确切位置?     

解决方法

        如果所选内容完全包含在单个文本节点中,则可以使用从所选内容中获得的范围的“ 1”方法来执行此操作。但是,这非常脆弱:如果选择不能在逻辑上包围在单个元素中(通常,如果范围跨越节点边界,尽管这不是精确的定义),则它不起作用。在一般情况下,要执行此操作,您需要一种更复杂的方法。 另外,IE <9中不支持DOM
Range
window.getSelection()
。对于这些浏览器,您将再次需要另一种方法。您可以使用我自己的Rangy之类的库来规范浏览器行为,并且您可能会发现该类应用程序模块对该问题很有用。 简单的``1''示例jsFiddle:http://jsfiddle.net/VRcvn/ 码:
function surroundSelection(element) {
    if (window.getSelection) {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var range = sel.getRangeAt(0).cloneRange();
            range.surroundContents(element);
            sel.removeAllRanges();
            sel.addRange(range);
        }
    }
}
    ,        
function wrapSelectedText() {       
    var selection= window.getSelection().getRangeAt(0);
    var selectedText = selection.extractContents();
    var span= document.createElement(\"span\");
    span.style.backgroundColor = \"yellow\";
    span.appendChild(selectedText);
    selection.insertNode(span);
}
Lorem ipsum dolor sit amet,consectetur adipiscing elit. Nam rhoncus  gravida magna,quis interdum magna mattis quis. Fusce tempor sagittis  varius. Nunc at augue at erat suscipit bibendum id nec enim. Sed eu odio  quis turpis hendrerit sagittis id sit amet justo. Cras ac urna purus,non rutrum nunc. Aenean nec vulputate ante. Morbi scelerisque sagittis  hendrerit. Pellentesque habitant morbi tristique senectus et netus et  malesuada fames ac turpis egestas. Nulla tristique ligula fermentum  tortor semper at consectetur erat aliquam. Sed gravida consectetur  sollicitudin. 

<input type=\"button\" onclick=\"wrapSelectedText();\" value=\"Highlight\" />
,        有可能的。您需要使用range API和Range.surroundContents()方法。它将内容包装所在的节点放在指定范围的开始处。 参见https://developer.mozilla.org/en/DOM/range.surroundContents     ,        仅当您选择的内容仅包含文本而不包含HTML时,aroundContents才起作用。这是一个更灵活的跨浏览器解决方案。这将插入如下范围:
<span id=\"new_selection_span\"><!--MARK--></span>
在选择之前,将跨度插入到最近的打开HTML标记之前。
var span = document.createElement(\"span\");
span.id = \"new_selection_span\";
span.innerHTML = \'<!--MARK-->\';

if (window.getSelection) { //compliant browsers
    //obtain the selection
    sel = window.getSelection();
    if (sel.rangeCount) {
        //clone the Range object
        var range = sel.getRangeAt(0).cloneRange();
        //get the node at the start of the range
        var node = range.startContainer;
        //find the first parent that is a real HTML tag and not a text node
        while (node.nodeType != 1) node = node.parentNode;
        //place the marker before the node
        node.parentNode.insertBefore(span,node);
        //restore the selection
        sel.removeAllRanges();
        sel.addRange(range);
    }
} else { //IE8 and lower
    sel = document.selection.createRange();
    //place the marker before the node
    var node = sel.parentElement();
    node.parentNode.insertBefore(span,node);
    //restore the selection
    sel.select();
}
    ,        请发现以下代码对于包装所有类型的span标签都将有所帮助。请仔细阅读代码,并为您的实现使用逻辑。
getSelectedText(this);
addAnnotationElement(this,this.parent);

function getSelectedText(this) {
    this.range = window.getSelection().getRangeAt(0);
    this.parent = this.range.commonAncestorContainer;
    this.frag = this.range.cloneContents();
    this.clRange = this.range.cloneRange();
    this.start = this.range.startContainer;
    this.end = this.range.endContainer;
}


function addAnnotationElement(this,elem) {
    var text,textParent,origText,prevText,nextText,childCount,annotationTextRange,span = this.htmlDoc.createElement(\'span\');

    if (elem.nodeType === 3) {
        span.setAttribute(\'class\',this.annotationClass);
        span.dataset.name = this.annotationName;
        span.dataset.comment = \'\';
        span.dataset.page = \'1\';
        origText = elem.textContent;            
        annotationTextRange = validateTextRange(this,elem);
        if (annotationTextRange == \'textBeforeRangeButIntersect\') {
            text = origText.substring(0,this.range.endOffset);
            nextText = origText.substring(this.range.endOffset);
        } else if (annotationTextRange == \'textAfterRangeButIntersect\') {
            prevText = origText.substring(0,this.range.startOffset);
            text = origText.substring(this.range.startOffset);
        } else if (annotationTextRange == \'textExactlyInRange\') {
            text = origText
        } else if (annotationTextRange == \'textWithinRange\') {
            prevText = origText.substring(0,this.range.startOffset);
            text = origText.substring(this.range.startOffset,this.range.endOffset);
            nextText = origText.substring(this.range.endOffset);
        } else if (annotationTextRange == \'textNotInRange\') {
            return;
        }
        span.textContent = text;
        textParent = elem.parentElement;
        textParent.replaceChild(span,elem);
        if (prevText) {
            var prevDOM = this.htmlDoc.createTextNode(prevText);
            textParent.insertBefore(prevDOM,span);
        }
        if (nextText) {
            var nextDOM = this.htmlDoc.createTextNode(nextText);
            textParent.insertBefore(nextDOM,span.nextSibling);
        }
        return;
    }
    childCount = elem.childNodes.length;
    for (var i = 0; i < childCount; i++) {
        var elemChildNode = elem.childNodes[i];
        if( Helper.isUndefined(elemChildNode.tagName) ||
            ! ( elemChildNode.tagName.toLowerCase() === \'span\' &&
            elemChildNode.classList.contains(this.annotationClass) ) ) {
            addAnnotationElement(this,elem.childNodes[i]);
        }
        childCount = elem.childNodes.length;
    }
}

  function validateTextRange(this,elem) {
    var textRange = document.createRange();

    textRange.selectNodeContents (elem);
    if (this.range.compareBoundaryPoints (Range.START_TO_END,textRange) <= 0) {
        return \'textNotInRange\';
    }
    else {
        if (this.range.compareBoundaryPoints (Range.END_TO_START,textRange) >= 0) {
            return \'textNotInRange\';
        }
        else {
            var startPoints = this.range.compareBoundaryPoints (Range.START_TO_START,textRange),endPoints = this.range.compareBoundaryPoints (Range.END_TO_END,textRange);

            if (startPoints < 0) {
                if (endPoints < 0) {
                    return \'textBeforeRangeButIntersect\';
                }
                else {
                    return \"textExactlyInRange\";
                }
            }
            else {
                if (endPoints > 0) {
                    return \'textAfterRangeButIntersect\';
                }
                else {
                    if (startPoints === 0 && endPoints === 0) {
                        return \"textExactlyInRange\";
                    }
                    else {
                        return \'textWithinRange\';
                    }
                }
            }
        }
    }
}
    

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-