除了特定元素之外,递归设置`display:none`

igl*_*vzx 1 javascript css

如果我想隐藏<div id="content">(包括 div#content其自身)内的所有元素,我可以使用以下CSS:

*
{
    visibility: hidden !important;
}

div#content, div#content *
{
    visibility: visible !important;
}
Run Code Online (Sandbox Code Playgroud)

关于这个解决方案需要注意的一点是,隐藏的元素仍占用空间.不幸的是,并非所有元素都具有相同的display属性,因此您不能简单地将visibility上面的内容替换为display.

使用JavaScript,如何将所有元素设置为属于<div id="#content">"family"的display: none

jfr*_*d00 7

一个通用的解决方案来改变最少的对象的样式,但要确保它#content和它的所有子元素都是可见的,需要一个算法来遍历#content并隐藏每个级别的所有兄弟,而不会隐藏其祖先#content.因为它始于#content和上升,它永远不会隐藏任何元素#content.

function hideAllExcept(id) {
    var el = document.getElementById(id);
    while (el && el != document.body) {
        // go one level up
        var parent = el.parentNode;
        // get siblings of our ancesotr
        var siblings = parent.childNodes;
        // loop through the siblings of our ancestor, but skip out actual ancestor
        for (var i = 0, len = siblings.length; i < len; i++) {
            if (siblings[i] != el && siblings[i].nodeType == 1) {
                // only operate on element nodes
                siblings[i].style.display = "none";
            }
        }
        el = parent;
    }
}

hideAllExcept("content");
Run Code Online (Sandbox Code Playgroud)

警告:第一个版本不会隐藏作为#content祖先兄弟节点的文本节点(#content之外的所有其他文本节点都被隐藏,因为它们的父节点是隐藏的).要隐藏这些文本节点,它们必须包含在<span>标记中,以便可以在<span>标记上设置样式,但我不知道OP是否需要该级别的复杂性或者希望文本节点以这种方式包装.

为了完整性,这里有一个版本,它将包装父兄弟文本节点,以便它们也可以设置为display: none.根据源HTML,可能需要也可能不需要:

function hideAllExcept(id) {
    var el = document.getElementById(id);
    while (el && el != document.body) {
        // go one level up
        var parent = el.parentNode;
        // get siblings of our ancesotr
        var siblings = parent.childNodes;
        // loop through the siblings of our ancestor, but skip out actual ancestor
        for (var i = 0, len = siblings.length; i < len; i++) {
            var node = siblings[i];
            if (node != el) {
                if (node.nodeType == 1) {
                    // only operate on element nodes
                    node.style.display = "none";
                } else if (node.nodeType == 3) {
                    // wrap text node in span object so we can hide it
                    var span = document.createElement("span");
                    span.style.display = "none";
                    span.className = "xwrap";
                    node.parentNode.insertBefore(span, node);
                    // Be wary of the dynamic siblings nodeList changing 
                    // when we add nodes.  
                    // It actually works here because we add one 
                    // and remove one so the nodeList stays constant.
                    span.appendChild(node);
                }
            }
        }
        el = parent;
    }
}

hideAllExcept("content");?
Run Code Online (Sandbox Code Playgroud)

一个工作演示:http://jsfiddle.net/jfriend00/yVWDx/