我有我的商店页面,想创建一个允许用户从手机上传照片的功能。我需要一个显示二维码的弹出窗口,关闭后,照片会出现在我的上一页上。
如何创建该弹出窗口?
我尝试过:
window.open("qr.html", "_blank", "left=100,top=100,width=320,height=320");
但它不能解决问题,我需要在此弹出窗口关闭后启动代码。 怎么办?
要实现您所描述的功能,您可以使用JavaScript的
window.open()
打开包含QR码的弹出窗口,然后使用window.addEventListener()
在弹出窗口关闭时监听事件。弹出窗口关闭后,您可以执行代码来处理上传的照片。
以下是有关如何执行此操作的分步指南:
qr.html
的 HTML 文件,用于显示 QR 码。您可以使用 JavaScript 库生成 QR 码,也可以根据需要使用 API 动态生成 QR 码。例如,您可以使用 qrcode.js
库:<!DOCTYPE html>
<html>
<head>
<title>QR Code Popup</title>
<script src="https://cdn.rawgit.com/davidshimjs/qrcodejs/gh-pages/qrcode.min.js"></script>
</head>
<body>
<div id="qrcode"></div>
<script>
const urlToEncode = "https://example.com"; // Replace with the URL you want to encode
const qrcode = new QRCode(document.getElementById("qrcode"), {
text: urlToEncode,
width: 256,
height: 256,
});
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>My Shop Page</title>
</head>
<body>
<!-- Your shop content here -->
<button id="uploadButton">Upload Photos</button>
<script>
document.getElementById("uploadButton").addEventListener("click", function () {
const popup = window.open("qr.html", "_blank", "left=100,top=100,width=320,height=320");
// Listen for the 'unload' event on the popup window
popup.addEventListener("unload", function () {
// Handle the event when the popup is closed
// This is the code you want to run after the popup is closed
handleUploadedPhotos();
});
});
function handleUploadedPhotos() {
// Code to handle the uploaded photos after the popup is closed
// For example, you can retrieve the uploaded photos and display them on the shop page.
// Implement this function according to your needs.
console.log("Photos uploaded and popup closed!");
}
</script>
</body>
</html>
上面的代码在“上传照片”按钮上设置了一个事件侦听器。单击该按钮时,会使用
qr.html
打开 window.open()
弹出窗口。然后,它向弹出窗口添加一个事件侦听器以检测它何时关闭。当弹出窗口关闭时,会执行 handleUploadedPhotos()
函数,其中可以包含处理上传照片并相应更新商店页面的代码。
请记住将
urlToEncode
中的 qr.html
变量替换为您希望二维码代表的 URL(例如,指向您的照片上传页面的链接)。
通过这种方法,您应该能够在弹出窗口中显示二维码,并在弹出窗口关闭后在主页上执行代码。