除了使用Undo之外,我认为没有办法删除内容可编辑的h1和h2标签.预期的行为是再次单击H1按钮应该关闭它,但它不会.还有一个“删除格式”按钮,但它只适用于粗体,斜体等项目.有没有办法通过JavaScript执行此操作?
编辑:结果必须删除打开和关闭H1标记,而不是用其他任何内容替换它.
请在此处查看简化的测试用例:
http://jsfiddle.net/kthornbloom/GSnbb/1/
最佳答案
我决定将我在评论中概述的方法实现到我的另一个答案:遍历所选范围内的节点并删除特定节点(在这种情况下,基于标记名称).
这是完整的演示.它不能在IE< = 8(缺少DOM范围和选择支持)中工作,但会在其他主要的当前浏览器中使用.一个问题是选择并不总是保留,但这并不难实现.
http://jsfiddle.net/gF3sa/1/
此示例包括elsewhere on SO的修改范围遍历代码.
function nextNode(node) {
if (node.hasChildNodes()) {
return node.firstChild;
} else {
while (node && !node.nextSibling) {
node = node.parentNode;
}
if (!node) {
return null;
}
return node.nextSibling;
}
}
function getRangeSelectedNodes(range,includePartiallySelectedContainers) {
var node = range.startContainer;
var endNode = range.endContainer;
var rangeNodes = [];
// Special case for a range that is contained within a single node
if (node == endNode) {
rangeNodes = [node];
} else {
// Iterate nodes until we hit the end container
while (node && node != endNode) {
rangeNodes.push( node = nextNode(node) );
}
// Add partially selected nodes at the start of the range
node = range.startContainer;
while (node && node != range.commonAncestorContainer) {
rangeNodes.unshift(node);
node = node.parentNode;
}
}
// Add ancestors of the range container,if required
if (includePartiallySelectedContainers) {
node = range.commonAncestorContainer;
while (node) {
rangeNodes.push(node);
node = node.parentNode;
}
}
return rangeNodes;
}
function getSelectedNodes() {
var nodes = [];
if (window.getSelection) {
var sel = window.getSelection();
for (var i = 0,len = sel.rangeCount; i < len; ++i) {
nodes.push.apply(nodes,getRangeSelectedNodes(sel.getRangeAt(i),true));
}
}
return nodes;
}
function replaceWithOwnChildren(el) {
var parent = el.parentNode;
while (el.hasChildNodes()) {
parent.insertBefore(el.firstChild,el);
}
parent.removeChild(el);
}
function removeSelectedElements(tagNames) {
var tagNamesArray = tagNames.toLowerCase().split(",");
getSelectedNodes().forEach(function(node) {
if (node.nodeType == 1 &&
tagNamesArray.indexOf(node.tagName.toLowerCase()) > -1) {
// Remove the node and replace it with its children
replaceWithOwnChildren(node);
}
});
}
removeSelectedElements("h1,h2,h3,h4,h5,h6");
原文链接:https://www.f2er.com/js/429799.html