之前做項目的時候用戶需要二維碼,本人小白一個就直接在網上找了代碼,下面說一說遇到的問題。
首先在頁面中加入jquery庫文件和qrcode插件
<script type="text/javascript" src="../qrcode/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="../qrcode/jquery.qrcode.min.js"></script>
然後在需要生成二維碼的地方引入
<div id="qrcode"></div>
最後是生成二維碼的js代碼
jQuery('#qrcode').qrcode({
render : "canvas",
width : 150,
height : 150,
text : utf16to8("www.baidu.com")
});
附上utf8轉換代碼
function utf16to8(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 type="text/javascript" src="../qrcode/jquery.jqprint-0.3.js"></script>
function printme() {
var img = document.getElementById("image");
var canvas = document.getElementsByTagName("canvas")[0];
img.src = canvas.toDataURL();
$("#image").jqprint({
debug : false,
importCSS : true,
printContainer : true,
operaSupport : false,
callBack : function() {
console.log("callBack");
}
});
}
<div id="qrcode"></div>
<label id="qrcodeInfo"></label>
<img id="image" src="" />
<input style="margin-left: 50px;" type="button" value="打印二維碼"
onclick="printme()" />
調用自帶的框架裏面的內容就可以了,這裏有個小問題,框架本身沒有callBack ,我爲了能設置返回值在框架的源碼裏面加了一句,就可以了。
有需要源碼的可以留言哦。