2014-02-13 85 views
3

我一直在寻找解决方案。 我想要一件事。当使用@media print {...}我想隐藏所有元素而不是一个。怎么做? 我有我不想隐藏的class =“print”,如何隐藏所有没有这个类的东西?CSS打印隐藏除一个元素之外的所有元素

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Untitled Document</title> 
<style> 
@media print { 
:not(.print) { 
    display: none 
} 
} 
</style> 
</head> 

<body> 
<div class="print"> 
    <p>neki lijepi tekst</p> 
    <p> test</p> 
</div> 
<div id="test"> ovo se ne vidi naa printu </div> 
<div id="tesft"> ovo se nedsfdf vidi naa printu </div> 
</body> 
</html> 
+0

这是'一件事'是其他元素的孩子,你也不想打印? –

+0

是身体的小孩 – FosAvance

+0

那么,除了身体。它是身体下面的顶级DOM元素吗? –

回答

4

这取决于你的DOM结构。

你要隐藏的每个顶级节点(因此,他们的子女)用CSS(display: none除了你要打印项目和所述项目的每一个父元素(即你不不想隐藏包含要打印的项目的顶级节点)。

你可以用一些javascript来设置它(相对)很容易 - jQuery会有所帮助。

  • 给你想打印一类的项目(S),如“printThis”
  • 分配身体的每一个顶级的孩子,被设置为display: none如“doNotPrint”
  • 找到一个类您想要打印的项目(通过“printThis”类)
  • 遍历DOM向每个父级移除您应用的类以隐藏所有内容(并且可能将hide类应用于进程中的所有同级)

没有测试,但在页面加载时运行这样的事情来设置类:

// to start, hide all top level nodes 
$('body').children().addClass('doNotPrint') 

// now we call this function passing in the 
// item to print 
function showItem($node) { 
    // remove the 'hide' class. This is moot 
    // until we loop to the top level node, at 
    // which point this takes affect 
    $node.removeClass('doNotPrint'); 
    // we don't want to print the siblings 
    // so we will hide those 
    $node.siblings().addClass('doNotPrint') 
    // now we check to see if this item has a parent 
    // and, if so... 
    if($node.parent().length){ 
     // ...we want to show the parent, hide its 
     // siblings, and then continue this process 
     // back to the top of the node tree 
     showItem($node.parent()); 
    } 
} 

showItem($('.printThis')); 

然后您打印的CSS将有:

.doNotPrint {display: none;} 
+0

@Musa我不认为'length'是必要的。父或者存在或它不 –

+1

你知道'.parent()'返回什么吗? – Musa

+0

@musa off去玩这个... :) BRB –

8

隐藏在身体没有一个print类中的每个子元素

body > * { display: none } 
.print { display: block } 

一旦没有文本节点直接在bodytis应该工作。

+2

如前所述,只有当要打印的项目是身体的直接后代时才能使用。 –

+0

@DA。你的意思是身体的一个孩子?...是的。 – Musa

+0

是的,我认为'孩子'和'直系后裔'在这里意味着同样的事情。是的,在这个例子中。但应该指出的是,这是解决方案的关键部分。 –

相关问题