Jquery生成条形码到网页以及打印条形码

背景

最新一个项目上涉及到生成条形码,并打印出来,个人经常写java,但是用后端去处理这个反而挺麻烦的。使用js是比较方便的,这里就简单地介绍一下。
在网上查了很多关于生成条形码的内容,就属JsBarcode用的最好,github地址:https://github.com/lindell/JsBarcode。对于生成条形码的延申,也可以好好查看。

使用环境

这个JsBarcode 的js插件式依赖于jquery库,你需要先把这个导入,然后再导入JsBarcode库。否则会出问题。

代码详解

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<script type="text/javascript" src="js/jquery2.1.4.min.js"></script>
<script type="text/javascript" src="js/JsBarcode.all.min.js"></script>
<script type="text/javascript">
    function myprint(){ 
      //直接调用浏览器打印功能
       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();
       //还原网页内容     
       window.document.body.innerHTML=bdhtml; 
    }
    function barcodeGen(){
        var barvalue=$("#barcodeValue").val();
        if(barvalue==""){
            alert("请输入条形码字符串!!")
        }else{
            $("#bcode").JsBarcode(barvalue);
        }
    }
</script>
<body>
    <hr>
    请输入要转成条形码的数字:<input type="text"  id="barcodeValue"> &nbsp;<a href="#" onClick="barcodeGen();" ><span> 生成条形码</span></a><br>
    <!--startprint-->
    <img id="bcode"/>
    <!--endprint-->
    <hr>
    <a href="#" onClick="myprint();" ><span> 打  印</span></a><br>
</body>
</html>

效果演示

这里写图片描述

程序源码:链接:https://pan.baidu.com/s/1QRywVK4bawzlwtzO4Xnswg 密码:qcf5
这里写图片描述

猜你喜欢

转载自blog.csdn.net/meiqi0538/article/details/81326825