2

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

4

2 回答 2

4

这是一个纯 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/

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

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

于 2012-07-16T13:26:59.217 回答
2
     $("font").attr("face", "");
    $("*").css("font", "");

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

于 2012-07-16T13:26:39.323 回答