Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript document.execCommand是否删除formatBlock格式?_Javascript_Html_Formatting_Contenteditable - Fatal编程技术网

JavaScript document.execCommand是否删除formatBlock格式?

JavaScript document.execCommand是否删除formatBlock格式?,javascript,html,formatting,contenteditable,Javascript,Html,Formatting,Contenteditable,如果我在这样的页面上格式化一段文本: document.execCommand('formatBlock', false, 'h1'); 如何删除此格式?我想document.execCommand('removeFormat',false,false)可以吗 在-块上发出document.execCommand('formatBlock',false,'div')将删除-标记并用-标记1替换它。这是否可行 1如果您没有使用IE,则可能必须找到父标记,然后使用innerHTML获取文本,并用i

如果我在这样的页面上格式化一段文本:

document.execCommand('formatBlock', false, 'h1');
如何删除此格式?

我想
document.execCommand('removeFormat',false,false)
可以吗

-块上发出
document.execCommand('formatBlock',false,'div')
将删除
-标记并用
-标记1替换它。这是否可行


1如果您没有使用IE,则可能必须找到父标记,然后使用innerHTML获取文本,并用innerHTML替换父标记和结束标记之间的原始数据。但是,这将删除所有格式。

我使用以下命令清除h1的效果:

document.execCommand('formatBlock', false, 'p');
您已将其格式更改为h1,因此我们可以用相同的方式将其更改回正常的段落格式。
如果您将每个段落放在a中,您也可以使用:

document.execCommand('formatBlock', false, 'div');

将格式设置为与其他块相同。

我遇到了同样的问题,需要删除包装文本的h1标记

我所做的是获取所选文本的父节点:

变量元素父节点= window.getSelection().getRangeAt(0).startContainer.parentNode

然后检查它的nodeName是否为“H1”;如果是,则将选定文本存储在选定的_文本变量中,然后删除节点本身:

elem_parent_node.remove()

那么

document.execCommand('insertText',false,select_text)


要用文本内容节点替换h1,请使用下面的代码。 对于完整的代码,您需要添加一些检查以确保删除所需的内容

const button=document.getElementsByTagName('button')[0]
addEventListener('click',event=>{
const selection=window.getSelection()
如果(!selection.isCollapsed){
selection.anchorNode.parentNode.replaceWith(selection.anchorNode)
}
})

一些文本

选择我,然后单击按钮 一些文本


单击以删除H1
似乎无法“撤消”格式化块。只要一个“formatBlock”是另一个块级HTML标记,您就可以用另一个“formatBlock”替换它。

事实并非如此。它可以删除粗体、斜体、下划线等格式,但不能删除HTML标记。除了没有很好的文档记录和IE不支持的
RemoveParaFormat
,我想不出任何
execCommand
可以从选择中删除HTML。也许一个正则表达式就应该做到这一点?如果有许多未使用的
div
标记随机浮动,通常会有问题吗?如果没有,这应该没问题。我认为这不是什么大问题。div并不是真正未使用的,我想,您在contentEditable元素中单击的文本被一个div标记包围(有效地替换了以前分配的标记),仅此而已。您在contentEditable元素中创建的每一行新行也被包装在一个div中。撤消是一个选项吗
document.execCommand(“Undo”,false,null)
不幸的是,Undo不是一个选项,因为它可能在不同的元素上执行多次,并且部分由用户控制,我不想撤消其间的所有更改。这很公平。我认为您的选择仅限于手动DOM操作。