使用jquery.qrcode生成二维码及常见问题的解决方案

移动端二维码弹出框,自适应屏幕尺寸:网址https://github.com/iyangyuan/qrcodebox

在线生成网址:http://tool.oschina.net/qr

 

一、jquery.qrcode.js介绍

jquery.qrcode.js 是一个纯浏览器 生成 QRcode 的 jQuery 插件((可以从https://github.com/jeromeetienne/jquery-qrcode 获取)),它使用非常简单,生成的 QRcode 无需下载图片,并且不依赖第三方服务,插件压缩之后大小小于 4K。

二、参数说明

  1. text     : "https://github.com/jeromeetienne/jquery-qrcode"  //设置二维码内容    
  2. render   : "canvas",//设置渲染方式 (有两种方式 table和canvas,默认是canvas)   
  3. width       : 256,     //设置宽度    
  4. height      : 256,     //设置高度    
  5. typeNumber  : -1,      //计算模式    
  6. correctLevel    : 0,//纠错等级  
  7. background      : "#ffffff",//背景颜色    
  8. foreground      : "#000000" //前景颜色 (二维码的条纹颜色) 

三、jquery.qrcode使用步骤

1. 引入文件    加载 jQuery 和 jquery.qrcode.js:

    
    

 2. 创建一个用于包含 QRcode 图片的 DOM 元素,比如 div:

//创建生产二维码的标签

3.通过下面代码生成 QRcode:

  最简单方式:jQuery('#qrcode').qrcode("https://blog.csdn.net/muzidigbig/");    

  自定义方式:jQuery('#qrcode').qrcode({render:'canvas',width: 64,height: 64,correctLevel:0,text: "https://blog.csdn.net/muzidigbig/"}); 

四、常见问题

1.在chorme浏览器中二维码生成成功后无法扫描解决方法

  //改成使用table的渲染方式,亲测支持各种各版本的浏览器 

       jQuery('#qrcode').qrcode({width: 200,height: 200,correctLevel:0,render: "table",text: "https://blog.csdn.net/muzidigbig/"}); 

 jQuery('#qrcode').qrcode({width: 200,height: 200,correctLevel:0,render: "table",text: "https://blog.csdn.net/muzidigbig/"}); 

 2.在微信或手机浏览器中生成的二维码无法扫描解决方法;

  //改成使用默认的渲染方式,支持微信和QQ内置浏览器及其它手机浏览器  

   jQuery('#qrcode').qrcode({width: 200,height: 200,correctLevel:0,text: "https://blog.csdn.net/muzidigbig/"}); 

 jQuery('#qrcode').qrcode({width: 200,height: 200,correctLevel:0,text: "https://blog.csdn.net/muzidigbig/"}); 

jquery-qrcode这个库是采用 charCodeAt() 这个方式进行编码转换的,这个方法默认会获取它的 Unicode 编码,一般的解码器都是采用UTF-8, ISO-8859-1等方式。

 英文是没有问题,如果是中文,一般情况下Unicode是UTF-16实现,长度2位,而UTF-8编码是3位,这样二维码的编解码就不匹配了。
 解决方式当然是,在二维码编码前把字符串转换成UTF-8,具体代码如下:

      jQuery("#qrcode").qrcode({
        width: 200,
        height: 200,
        correctLevel: 0,
        foreground: 'pink',
        text: utf16to8("木子大大:https://blog.csdn.net/muzidigbig/"),
      });
      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;
      }
    });

五、上面生成方式的演示代码:



  
    
    
    
    Document
  
  
    

效果:

使用jquery.qrcode生成二维码及常见问题的解决方案_第1张图片

你可能感兴趣的:(jq生成二维码)