gpt4 book ai didi

javascript - 开始范围以插入 Div

转载 作者:太空宇宙 更新时间:2023-11-04 16:01:21 27 4
gpt4 key购买 nike

我正在尝试创建一个 Google Chrome 扩展程序,用户可以在其中突出显示页面上的文本,并且在文本的开头会出现一张笑脸。我找到了 this演示如何存储和检索范围的网站。我的问题是如何获得插入

的范围的开始?

var selection = storeSelection(window.getSelection());
var selectionRange = restoreSelection(selection);
console.log( selectionRange.startContainer.offsetLeft ); //undefined


function makeXPath (node, currentPath) {
/* this should suffice in HTML documents for selectable nodes, XML with namespaces needs more code */
currentPath = currentPath || '';
switch (node.nodeType) {
case 3:
case 4:
return makeXPath(node.parentNode, 'text()[' + (document.evaluate('preceding-sibling::text()', node, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotLength + 1) + ']');
case 1:
return makeXPath(node.parentNode, node.nodeName + '[' + (document.evaluate('preceding-sibling::' + node.nodeName, node, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotLength + 1) + ']' + (currentPath ? '/' + currentPath : ''));
case 9:
return '/' + currentPath;
default:
return '';
}
}

function storeSelection (selectionObject) {
if (typeof window.getSelection != 'undefined') {
var selection = selectionObject;
var range = selection.getRangeAt(0);
if (range != null) {
selectionObject = makeXPath(range.startContainer) + '|' + range.startOffset + '|' + makeXPath(range.endContainer) + '|' + range.endOffset;
return selectionObject
}
}
}

function restoreSelection (selectionObject) {
var selectionDetails = selectionObject;
if (selectionDetails != null) {
selectionDetails = selectionDetails.split(/\|/g);
if (typeof window.getSelection != 'undefined') {
var range = document.createRange();
range.setStart(document.evaluate(selectionDetails[0], document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue, Number(selectionDetails[1]));
range.setEnd(document.evaluate(selectionDetails[2], document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue, Number(selectionDetails[3]));
return range;
}
}
}

最佳答案

非常简单,因为您只需要担心 Chrome:

// Get the range
var range = document.getSelection().getRangeAt(0);
// Collapse it to the start
range.collapse(true);
// insert your node
range.insertNode(node);

这是一个工作示例:http://jsfiddle.net/L5Qqk/ .请注意,它一直在移动笑脸,因为我总是添加相同的节点。如果您每次都创建一个新节点,则会添加多个笑脸。

关于javascript - 开始范围以插入 Div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9763691/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com