更改最少对象样式的通用解决方案,但确保其#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");
警告:这个第一个版本不隐藏作为#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");
还有一个工作演示:http: //jsfiddle.net/jfriend00/yVWDx/