前端-打印指定内荣容

 

正文:

  打印网页内指定的内容:共有4种方案:

  

方案一.1:利用js操作

html内容如下:

<script language="javascript"> 
function preview() 
{ 
bdhtml=window.document.body.innerHTML; 
sprnstr="<!--startprint-->"; 
eprnstr="<!--endprint-->"; 
prnhtml=bdhtml.substr(bdhtml.indexOf(sprnstr)+17); 
prnhtml=prnhtml.substring(0,prnhtml.indexOf(eprnstr)); 
window.document.body.innerHTML=prnhtml; 
window.print(); 
} 
</script>

<div>文件头部,不打印出来的内容。。。</div>
<div>文件头部,不打印出来的内容。。。</div>
<div>文件头部,不打印出来的内容。。。</div>
<!--startprint-->
<div>这是被打印出来的内容</div>
<div>这是被打印出来的内容</div>
<div>这是被打印出来的内容</div>
<div>这是被打印出来的内容</div>
<!--endprint-->
<div>文件尾部,不打印出来的内容。。。</div>
<div>文件尾部,不打印出来的内容。。。</div>
<div>文件尾部,不打印出来的内容。。。</div>
<input type="button" name="print" value="预览并打印" onclick="preview()">

 

方案一.2:
<script language="javascript" type="text/javascript">
    function printpage(myDiv){    
    //var newstr = document.all.item(myDiv).innerHTML; 
    var newstr = document.getElementById(myDiv).innerHTML;
    var oldstr = document.body.innerHTML; 
    document.body.innerHTML = newstr; 
    window.print(); 
    document.body.innerHTML = oldstr; 
    return false; 
    } 
    </script>
   <div id="myDiv">Content</div>
<input type="button" id="bt" onclick="javascript:printpage('myDiv')"   value="打印" />
方案一.3:
<html> 
<head> 
<title>jquery 打印指定区域内容</title> 
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
function printHtml(html) {
var bodyHtml = document.body.innerHTML;
document.body.innerHTML = html;
window.print();
document.body.innerHTML = bodyHtml;
}
function onprint() {
var html = $("#printArea").html();
printHtml(html);
}
</script>
</head>
<body>
<div>
<div id="printArea" style="width: 500px; text-align: left;">
打印区域~~~~
</div>
<br />
<div>
<input type="button" id="btnPrint" onclick="onprint()" value="print" />
</div>
</div>
</body>
</html>

 

方案二:JavaScript打印函数
<script>
function myPrint(obj){
    //打开一个新窗口newWindow
    var newWindow=window.open("打印窗口","_blank");
    //要打印的div的内容
    var docStr = obj.innerHTML;
    //打印内容写入newWindow文档
    newWindow.document.write(docStr);
    //关闭文档
    newWindow.document.close();
    //调用打印机
    newWindow.print();
    //关闭newWindow页面
    newWindow.close();
}
myprint()调用方法:
myPrint(document.getElementById('printDivID'));
</script>
<div id="print">
<hr />
   打印演示区域,点击打印后会在新窗口加载这里的内容!
<hr />
</div>
<button onclick="myPrint(document.getElementById('print'))">打 印</button>

 

方案三:采用print的事件,显隐内容
<script type="text/javascript">  

  //自动在打印之前执行  
    window.onbeforeprint = function(){  
        $("#test").hide();  
    }  
  
    //自动在打印之后执行  
    window.onafterprint = function(){  
        $("#test").show();  
    }  
</script>  
  
<div id="test">这段文字不会被打印出来</div> 

详情见:W3CSchoolHTML onbeforeprint 事件属性

 
参考:js print打印网页指定区域内容
 

posted on 2016-04-15 16:40  是知也  阅读(1826)  评论(0编辑  收藏  举报

导航