使用HTML、CSS和jQuery生成QR码
二维码生成器是一种应用程序,它可以将任何所需的文本数据存储到二维码中,以后可以用二维码扫描仪扫描,以显示存储的信息。这个二维码可以在任何地方使用,例如,在海报或网站上,让用户获得额外的信息。这个应用程序将允许用户输入所需的数据,并将其保存为QR码的PNG或SVG图像。
方法:为了生成QR码,我们将使用Google Charts API。使用jQuery,根据API返回的图像来更新要显示的QR码图像。
将要使用的API端点如下。
https://chart.googleapis.com/chart?chs=150×150&cht=qr&chl=Hello%20world
对URL的解释:
- Google Chart Infographics的根URL是https://chart.googleapis.com/chart 。这可以用所需的参数来指定,以获得所需的输出。
- chs参数表示二维码图像的大小,单位为像素。
- cht参数表示要创建的图像的类型。值 “qr “将被用来生成一个QR码。
- chl参数表示要在QR码中编码的文本或URL数据。
示例:
<!DOCTYPE html>
<html>
<head>
<!-- Include Bootstrap for styling -->
<link rel="stylesheet" href=
"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
<style>
.qr-code {
max-width: 200px;
margin: 10px;
}
</style>
<title>QR Code Generator</title>
</head>
<body>
<div class="container-fluid">
<div class="text-center">
<!-- Get a Placeholder image initially,
this will change according to the
data entered later -->
<img src=
"https://chart.googleapis.com/chart?cht=qr&chl=Hello+World&chs=160x160&chld=L|0"
class="qr-code img-thumbnail img-responsive" />
</div>
<div class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-2"
for="content">
Content:
</label>
<div class="col-sm-10">
<!-- Input box to enter the
required data -->
<input type="text" size="60"
maxlength="60" class="form-control"
id="content" placeholder="Enter content" />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<!-- Button to generate QR Code for
the entered data -->
<button type="button" class=
"btn btn-default" id="generate">
Generate
</button>
</div>
</div>
</div>
</div>
<script src=
"https://code.jquery.com/jquery-3.5.1.js">
</script>
<script>
// Function to HTML encode the text
// This creates a new hidden element,
// inserts the given text into it
// and outputs it out as HTML
function htmlEncode(value) {
return ('<div/>').text(value)
.html();
}
(function () {
// Specify an onclick function
// for the generate button
('#generate').click(function () {
// Generate the link that would be
// used to generate the QR Code
// with the given data
let finalURL =
'https://chart.googleapis.com/chart?cht=qr&chl=' +
htmlEncode(('#content').val()) +
'&chs=160x160&chld=L|0'
// Replace the src of the image with
// the QR code image
$('.qr-code').attr('src', finalURL);
});
});
</script>
</body>
</html>
输出:
jQuery是一个开源的JavaScript库,它简化了HTML/CSS文档之间的交互,它以其 “少写多做 “的理念而广为人知。
你可以通过学习这个jQuery教程和jQuery实例,从基础开始学习jQuery。