QRCode.js:使用 JavaScript 生成二維碼

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ko" lang="ko">
<head>
<title>Javascript 二維碼生成庫:QRCode</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no" />
<script type="text/javascript" src="http://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="http://static.runoob.com/assets/qrcode/qrcode.min.js"></script>
</head>
<body>
<input id="text" type="text" value="http://www.runoob.com" style="width:80%" /><br />
<div id="qrcode" style="width:100px; height:100px; margin-top:15px;"></div>

<script type="text/javascript">
var qrcode = new QRCode(document.getElementById("qrcode"), {
    width : 100,
    height : 100
});

function makeCode () {        
    var elText = document.getElementById("text");
    
    if (!elText.value) {
        alert("Input a text");
        elText.focus();
        return;
    }
    
    qrcode.makeCode(elText.value);
}

makeCode();

$("#text").
    on("blur", function () {
        makeCode();
    }).
    on("keydown", function (e) {
        if (e.keyCode == 13) {
            makeCode();
        }
    });
</script>
</body>
</html>

查看在線樣例:  http://www.runoob.com/try/try.php?filename=tryhtml5_QRCodejavascript


什麼是 QRCode.js?

QRCode.js 是一個用於生成二維碼的 JavaScript 庫。主要是經過獲取 DOM 的標籤,再經過 HTML5 Canvas 繪製而成,不依賴任何庫。php


基本用法

<div id="qrcode"></div> <script type="text/javascript"> new QRCode(document.getElementById("qrcode"), "http://www.runoob.com"); // 設置要生成二維碼的連接 </script>

或者使用一些可選參數設置:css

var qrcode = new QRCode("test", { text: "http://www.runoob.com", width: 128, height: 128, colorDark : "#000000", colorLight : "#ffffff", correctLevel : QRCode.CorrectLevel.H });

一樣咱們能夠使用如下方法:html

qrcode.clear(); // 清除代碼 qrcode.makeCode("http://www.w3cschool.cc"); // 生成另一個二維碼

瀏覽器支持

支持該庫的瀏覽器有:IE6~10, Chrome, Firefox, Safari, Opera, Mobile Safari, Android, Windows Mobile, 等。html5


實例代碼

HTML 代碼

<input id="text" type="text" value="http://www.runoob.com" /><br /> <div id="qrcode"></div>

CSS 代碼

#qrcode { width:160px; height:160px; margin-top:15px; }

JavaScript 代碼

var qrcode = new QRCode("qrcode"); function makeCode () { var elText = document.getElementById("text"); if (!elText.value) { alert("Input a text"); elText.focus(); return; } qrcode.makeCode(elText.value); } makeCode(); $("#text"). on("blur", function () { makeCode(); }). on("keydown", function (e) { if (e.keyCode == 13) { makeCode(); } });
相關文章
相關標籤/搜索