<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>测试</title> <script src="https://cdn.bootcss.com/jsbarcode/3.8.0/JsBarcode.all.min.js"></script> </head> <body> <h1>条形码生成测试</h1> <div class="box"> <img id="barcode" /> </div> <input type="text" id="content" placeholder="请输入条码内容"/> <input type="button" id="autoIma" value="生成" onclick="CreateIma()"/> <input type="button" id="btnsavaImg" value="保存图片到本地" onclick="Download()" /> <script> //生成条码 function CreateIma() { var content = document.getElementById('content').value; if (content == undefined || content == "") { alert("请输入条码内容!"); return; }; var barcode = document.getElementById('barcode'), //str = "chenyanbin", options = { format: "CODE128", displayValue: true, fontSize: 18, height: 100 }; JsBarcode(barcode, content, options); //原生JS方式 // $('#barcode').JsBarcode(string, options); //jQuery方式 } //将生成的条形码保存至本地 function Download() { // 通过选择器获取img元素 var img = document.getElementById('barcode') // 将图片的src属性作为URL地址 var url = img.src var a = document.createElement('a') var event = new MouseEvent('click') a.download = name || '下载图片名称' a.href = url a.dispatchEvent(event) //根据A标签的属性来搞事情 }; </script> </body> </html>