实现的效果:
首先,需要设置一个按钮,触发生成二维码的事件:
<button type="button" class="btn btn-info btn-3d disabled" id="QRCodeBtn" data-toggle="modal" data-target="#qrCodeModal">二维码</button>
我用的模态框进行显示的,所以还需要写一个对应的模态框:
<!-- 二维码 -->
<div class="modal fade" id="qrCodeModal" tabindex="-1" role="dialog" aria-labelledby="qrCodeModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="qrCodeModalLabel">二维码</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<p class="subtitle">请用 扫码</p>
</div>
<div class="modal-body">
<div id="qrcode" class="qrcode"></div>
</div>
</div>
</div>
</div>
接下来就是重头戏:怎么生成二维码,主要是在js部分实现。我使用的是qrcode。
安装:
npm install qrcode
或者直接引入(qrcode.min.js是qrcode库的压缩版本
):
<script src="https://cdn.jsdelivr.net/npm/qrcode@1.4.4"></script>
<script src="https://cdn.jsdelivr.net/npm/qrcode@1.4.4/build/qrcode.min.js"></script>
处理逻辑:
// 生成二维码
$('#QRCodeBtn').removeClass('disabled');
// 当模态框完全显示时触发
$('#qrCodeModal').on('shown.bs.modal', function () {
// 在显示之前移除之前的事件处理程序
$('#qrCodeModal').off('shown.bs.modal');
// 使用正则表达式提取 name 参数和文件名
// const match = artic.webFileName.match(/\/Project\/file\/File\/.*?name=(.*?)\.glb/);
const match = artic.webFileName.match(/name=(\.\.\/[^\&]+\.glb)/);
if (match && match[1]) {
const webName = match[1].replace(/\.\.\//, '');
const webUrl = `http://127.0.0.1:8080/Project/file/webFile/${webName}`;
console.log('webUrl:', webUrl);
const qrcode = new QRCode(document.getElementById("qrcode"), {
text: webUrl,
width: 220,
height: 220,
});
} else {
console.error('Failed');
}
});
// 当按钮被点击时显示模态框
$('#QRCodeBtn').on('click', function () {
$('#qrCodeModal').modal('show');
});