使用jquery-qrcode產生二維碼,jquery-qrcode
二維碼
java方面二維碼相關工具大概有qrcode和zxing,
但是一般來說應用二維碼比較多的是產生,掃描用的比較少,
而qrcode和zxing是兩者都有,所以比較臃腫。
jquery-qrcode
官網:
說明:jquery的一個外掛程式,jquery-qrcode可以利用js產生二維碼,效果不錯。這裡做一下封裝,讓使用起來更簡單。
引入
需要引入jquery和jquery-qrcode,這兩個在static cdn上都有,直接引用就可以了,
另外還需要一段中文轉碼的js,一共需要引入:
<!-- jquery-1.11.1 --> <script type="text/javascript" src="http://cdn.staticfile.org/jquery/1.11.1/jquery.min.js"></script> <!-- jquery-qrcode --> <script type="text/javascript" src="http://cdn.staticfile.org/jquery.qrcode/1.0/jquery.qrcode.min.js"></script> <!-- 中文轉碼 --> <script type="text/javascript"> function qcodetochar(str){ var out, i, len, c; out = ""; len = str.length; for (i = 0; i < len; i++) { c = str.charCodeAt(i); if ((c >= 0x0001) && (c <= 0x007F)) { out += str.charAt(i); } else if (c > 0x07FF) { out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F)); out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F)); out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F)); } else { out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F)); out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F)); } } return out; }; </script>
封裝
封裝是為了更好的使用,可以直接傳str或者一個設定物件,具體如下:
/** * 產生二維碼 * text:待產生文字 * type:中文還是英文,cn為中文 * render:展示方式,table為表格方式 * width:寬度 * height:高度 * 註:需要引入<@jsfile 'qrcode'/> */$.fn.qcode = function(options){ if(options){ var opt = {}; if(typeof options == 'string'){ opt.text = options; }else{ if(options.text) opt.text = options.text; if(options.type && options.type == 'ch') opt.text = qcodetochar(opt.text); if(options.render && options.render == 'table') opt.render = options.render; if(options.width) opt.width = options.width; if(options.height) opt.height = options.height; } $(this).qrcode(opt); }};
使用
1.頁面需要一個div,並給一個id
2.$('#test').qcode({});
樣本
簡單非中文產生二維碼:
$('#test').qcode('123');
自訂配置產生二維碼:
$('#test').qcode({ text : '你好', type : 'cn', width : 100, height : 100});
更多
更多文章請瀏覽:http://uikoo9.com/blog/list