gpt4 book ai didi

javascript - 删除除 input#cursor 之外的选定(突出显示的元素)

转载 作者:行者123 更新时间:2023-12-02 20:04:17 25 4
gpt4 key购买 nike

我有这个函数可以删除选定的(光标)突出显示的元素:

function deleteSelection() {
if (window.getSelection) {
// Mozilla
var selection = window.getSelection();
if (selection.rangeCount > 0) {
window.getSelection().deleteFromDocument();
window.getSelection().removeAllRanges();
}
} else if (document.selection) {
// Internet Explorer
var ranges = document.selection.createRangeCollection();
for (var i = 0; i < ranges.length; i++) {
ranges[i].text = "";
}
}
}

我真正想做的是删除所有光标突出显示的元素,除了 input#cursor 元素。

编辑:

假设我用光标突出显示这些元素:

<span>a</span>
<span>b</span>
<input type='text' id = 'cursor' />
<span>c</span>
<span>d</span>

在键盘上,此函数不应删除 <input> ...只有<span>

最佳答案

唷,这比预想的要难一点!

这是代码,我已经在 IE8 和 Chrome 16/FF5 中测试过。我用来测试的JSFiddle可用here 。 AFAIK,这可能是您将获得的最佳性能。

我用于 Moz 的文档:Selection , Range , DocumentFragment 。即:TextRange

function deleteSelection() {
// get cursor element
var cursor = document.getElementById('cursor');

// mozilla
if(window.getSelection) {
var selection = window.getSelection();
var containsCursor = selection.containsNode(cursor, true);

if(containsCursor) {
var cursorFound = false;
for(var i=0; i < selection.rangeCount; i++) {
var range = selection.getRangeAt(i);
if(!cursorFound) {
// extracts tree from DOM and gives back a fragment
var contents = range.extractContents();
// check if tree fragment contains our cursor
cursorFound = containsChildById(contents, 'cursor');
if(cursorFound) range.insertNode(cursor); // put back in DOM
}
else {
// deletes everything in range
range.deleteContents();
}
}
}
else {
selection.deleteFromDocument();
}
// removes highlight
selection.removeAllRanges();
}
// ie
else if(document.selection) {
var ranges = document.selection.createRangeCollection();
var cursorFound = false;
for(var i=0; i < ranges.length; i++) {
if(!cursorFound) {
// hacky but it will work
cursorFound = (ranges[i].htmlText.indexOf('id=cursor') != -1);
if(cursorFound)
ranges[i].pasteHTML(cursor.outerHTML); // replaces html with parameter
else
ranges[i].text = '';
}
else {
ranges[i].text = '';
}
}
}
}

// simple BFS to find an id in a tree, not sure if you have a
// library function that does this or not
function containsChildById(source, id) {
q = [];
q.push(source);

while(q.length > 0) {
var current = q.shift();
if(current.id == id)
return true;

for(var i=0; i < current.childNodes.length; i++) {
q.push(current.childNodes[i]);
}
}

return false;
}

关于javascript - 删除除 input#cursor 之外的选定(突出显示的元素),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7640469/

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