删除所有与内联字体相关的标记,即使它在内联样式中也是如此

Remove all inline font related tags even if its within an inline style

本文关键字:样式 字体 删除      更新时间:2023-11-01

我有一个DOM,在这个DOM中,我加载了整个网页的HTML。我想删除所有与字体相关的标签,即使它在样式标签中。

这里有一个纯Javascript函数,它将把任何指定的标签集转换为<span>:

function stripFonts(el, tags) {
    if (el.tagName && el.tagName in tags) {
        // replace the element with a span
        var old = el, el = document.createElement('span');
        old.parentNode.replaceChild(el, old);
        // and move the children
        while (old.hasChildNodes()) {
            el.appendChild(old.firstChild);
        }
    }
    // recursive test all of this node's children
    var child = el.firstChild;
    while (child) {
        child.removeAttribute('style');  // NB: removes *all* style attributes
        stripFonts(child, tags);
        child = child.nextSibling;
    }
}
var tags = { 'B': 1, 'FONT': 1, 'STRIKE': 1 };

演示在http://jsfiddle.net/alnitak/4fBRQ/

使用<span>简化了代码,因为它维护了原始DOM树,并避免了将相邻的文本节点折叠在一起的需要。

添加要剥离的额外标签是微不足道的。它将需要一些额外的工作来处理特定于字体的内联样式标记,尽管删除每个style属性很容易,如下所示。

     $("font").attr("face", "");
    $("*").css("font", "");

您可以使用jQuery 清除font元素的事实属性并清除DOM中的所有css中的font feom