尝试在范围上使用 setStart 和 setEnd 时出错:未捕获 IndexSizeError:无法在“范围”上执行“setEnd”

2024-01-09

当我尝试使用范围时,我在控制台中收到此错误:

Uncaught IndexSizeError: Failed to execute 'setEnd' on 'Range': The offset 2 is larger than or equal to the node's length (0).

这是我的脚本:

<script type="text/javascript">
    function gotMark() {
        var range = document.createRange();
        var startNode = document.getElementById("dividTeste1").firstChild;

        range.setStart(startNode, 0);
        range.setEnd(startNode, 2);

        var newNode = document.createElement("span");
        range.surroundContents(newNode);
    }
</script>

和页面:

<div class="ui-block-a" id="divid" value="div1">
    <div style="background-color: black; color: white; padding: 20px;" id="divid2">
        <h2>London</h2>
        <p id="dividTeste1">London is the capital city of England. It is the most
            populous city in the United Kingdom, with a metropolitan area of
            over 13 million inhabitants.</p>
    </div>
        
    <div style="background-color: black; color: white; padding: 20px;" id="divid2">
        <h2>London</h2>
        <p id="dividTeste2">London is the capital city of England. It is the most
            populous city in the United Kingdom, with a metropolitan area of
            over 13 million inhabitants.</p>
    </div>
</div>
<input type="button" value="Marcar com range" onClick="gotMark()"
        id="marcarconranger12" />

我尝试按照以下说明进行操作dom range.setStart / setEnd https://stackoverflow.com/a/27462125/4395789选择开始和结束位置。


我用一行找到了错误的解决方案:

function gotMark() {
    var range = document.createRange();
    var startNode = document.getElementById("dividTeste1").firstChild;

    range.setStart(startNode, 0);
    range.setEnd(startNode, 2);

    var newNode = document.createElement("span");
    newNode.className = 'highlight-yellow'; // <-- added

    range.surroundContents(newNode);
}

现在选择已经跨越了。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

尝试在范围上使用 setStart 和 setEnd 时出错:未捕获 IndexSizeError:无法在“范围”上执行“setEnd” 的相关文章

随机推荐