IE 9 Standards Mode: normalize() method does not work

五迷三道 提交于 2019-12-06 01:50:54

I experienced this issue on IE 11, but after I tried "Reset Internet Explorer Settings", normalize() was behaving right. In any case, I wrote a function that does a "normalize" if IE is broken.

(function () {
    function checkIfNormalizeOk() {
        var p = document.createElement('p');

        // you can not put empty strings -- put blank strings instead
        p.appendChild( document.createTextNode(' ') );
        p.appendChild( document.createTextNode(' ') );
        p.appendChild( document.createTextNode(' ') );

        document.getElementsByTagName('head')[0].appendChild(p);
        p.normalize();
        var isNormalizeOk = (p.childNodes.length === 1);
        document.getElementsByTagName('head')[0].removeChild(p);
        return isNormalizeOk;
    }

    function getNextNode(node, ancestor, isOpenTag) {
        if (typeof isOpenTag === 'undefined') {
            isOpenTag = true;
        }
        var next;
        if (isOpenTag) {
            next = node.firstChild;
        }
        next = next || node.nextSibling;
        if (!next && node.parentNode && node.parentNode !== ancestor) {
            return getNextNode(node.parentNode, ancestor, false);
        }
        return next;
    }

    var isNormalizeOk = checkIfNormalizeOk();
    window.normalizeEl = function (el) {
        if (isNormalizeOk) {
            el.normalize();
        } else {
            var adjTextNodes = [], nodes, node = el;
            while ((node = getNextNode(node, el))) {
                if (node.nodeType === 3 && node.previousSibling && node.previousSibling.nodeType === 3) {
                    if (!nodes) {
                        nodes = [node.previousSibling];
                    }
                    nodes.push(node);
                } else if (nodes) {
                    adjTextNodes.push(nodes);
                    nodes = null;
                }
            }

            adjTextNodes.forEach(function (nodes) {
                var first;
                nodes.forEach(function (node, i) {
                    if (i > 0) {
                        first.nodeValue += node.nodeValue;
                        node.parentNode.removeChild(node);
                    } else {
                        first = node;
                    }
                });
            });
        }
    };
}());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!