[英]Print HTML-page with div that has been clicked on and hide the rest
我有一個HTML頁面,其中包含許多不同的DIV,我想打印出用戶單擊的DIV並隱藏所有其余部分。
有人可以告訴我如何使用Javascript執行此操作嗎?
<html>
<head>
<title>Print Demo</title>
<script type="text/javascript">
<!-- MY JAVASCRIPT FUNCITON -->
</script>
</head>
<body>
<div id="div1">
<a href="<JSMethod>">Print the page with this div</a>
</div>
<div id="div2">
<a href="<JSMethod>">Print the page with this div</a>
</div>
<div id="div3">
<a href="<JSMethod>">Print the page with this div</a>
</div>
</body>
</html>
隱藏元素意味着將其style.display
屬性設置為"none"
。 顯示表示將其設置為div元素的"block"
。
與getElementsByTagName
結合使用,您可以完成此操作: http : //jsfiddle.net/b9cgM/ 。
function show(elem) {
// hide all divs initially
var allDivs = document.getElementsByTagName("div");
for(var i = 0; i < allDivs.length; i++) {
allDivs[i].style.display = "none";
}
// show the appropriate div
elem.parentNode.style.display = "block"; // parent of the <a> is the <div> to show
}
您可以將事件綁定為<a href="#" onclick="show(this); return false;">
。 然后將元素( this
)傳遞給show
。
附帶說明,jQuery之類的庫使此操作變得更加容易。 您可能想檢查一下(盡管如果唯一的用例是這種情況,我不建議將其包括在內)。
這僅僅是為了擴展pimvdb的答案 。
jQuery的:
$("a").on("click", function(){
$("div").hide();
$(this).parent().show();
});
或按照建議:
$("a").on("click", function(){
$("div").hide();
$(this).closest("div").show();
});
抱歉,在js中只有window.print()可以打印,這意味着您只能打印整個窗口。 如果您希望某些人能夠打印您的文檔,請使用CSS使其可打印。 例如,也許您希望導航消失以進行打印,但是將頁面標題,網站名稱以及頁面URL保留在那里(有時,如Firefox之類的瀏覽器會因為過長而將其切斷)。 有時某些網站會奪走瀏覽器控件,並犯下使您沒有打印按鈕的錯誤-這是一個在線購買網站...以前發生過。
<style type="text/css">
@media print {
.boxGreen {
padding:10px;
border-color:green;
border-style:dashed;
border-width:thin;
}
}
@media screen {
.boxGreen {
padding:10px;
border-color:green;
border-style:dashed;
border-width:thin;
}
}
</style>
您可以執行onclick="switchtodiv('someid')"
,然后在div之后執行以下操作:
<div onclick="switchtodiv('span1')">ClickMe<span id="span1">some content</span></div>
<div onclick="switchtodiv('span2')">ClickMe<span id="span2">some content</span></div>
<div onclick="switchtodiv('span3')">ClickMe<span id="span3">some content</span></div>
<!--you can generate these divs using a for statement...-->
<script type="text/javascript">
//switchdiv allows only 1 div tobe
function switchdiv(id) {
var ids=new Array('span1','span2','span3');
var i;
for (i=0; i < ids.length; i++) {
if (ids[i] == id) {
document.getElementById(ids[i]).style.visibility='visible';
document.getElementById(ids[i]).style.display='block';
} else {
document.getElementById(ids[i]).style.visibility='hidden';
document.getElementById(ids[i]).style.display='none';
}
}
}
</script>
您可以使用JavaScript函數(例如document.getElementById(id))隱藏其他兩個div
所以在您的函數中,您可以使用
function hide1() {
document.getElementById(div2).style.display = "none";
document.getElementById(div3).style.display = "none";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.