使用 html 页面编辑精确定位文本文件选中

如下是一个实例,实现了文本的换行,选中以及滚动到选中文本位置的功能?
<html style='height:100%;'>
<head>
    <meta charset='UTF-8' />
</head>
<body style='height:100%;padding:0;margin:0;border-width:0;'>
    <div id="content" contenteditable='true' style='height: 100%; width: 100%; white-space: pre-wrap; overflow-y: scroll;'>
    </div>
    <script>
        var str = "xxx";
        var div = document.getElementById('content');
        div.textContent = decodeURIComponent(str);
    </script>
</body>
</html>

 

var startIndex = 100;
var endIndex = 120;
var range = document.createRange();
var selection = window.getSelection();
var divElement = document.getElementById('content');
range.setStart(divElement.firstChild, startIndex);
range.setEnd(divElement.firstChild, endIndex);
selection.removeAllRanges();
selection.addRange(range);

// 让选定内容滚动到可见区域
var rect = range.getBoundingClientRect();
divElement.scrollTop = rect.top - rect.height;
divElement.focus();

 

posted on 2024-03-20 19:45  空明流光  阅读(17)  评论(0编辑  收藏  举报

导航