90 lines
2.7 KiB
JavaScript
90 lines
2.7 KiB
JavaScript
(function () {
|
|
var mask = document.getElementById("searchDialog");
|
|
if (!mask) return;
|
|
|
|
var headerForm = document.querySelector("form.header-search");
|
|
var headerInput = headerForm
|
|
? headerForm.querySelector('input[name="q"]')
|
|
: null;
|
|
|
|
var input = mask.querySelector('[data-search-dialog-input]');
|
|
var form = mask.querySelector('[data-search-dialog-form]');
|
|
|
|
function isMobile() {
|
|
try {
|
|
return window.matchMedia("(max-width: 767px)").matches;
|
|
} catch (e) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
function openDialog(initialValue) {
|
|
if (initialValue != null && input) {
|
|
input.value = String(initialValue || "");
|
|
}
|
|
mask.classList.add("is-open");
|
|
mask.setAttribute("aria-hidden", "false");
|
|
document.body.style.overflow = "hidden";
|
|
|
|
requestAnimationFrame(function () {
|
|
requestAnimationFrame(function () {
|
|
if (input) input.focus();
|
|
if (input && typeof input.select === "function") {
|
|
input.select();
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
function closeDialog() {
|
|
mask.classList.remove("is-open");
|
|
mask.setAttribute("aria-hidden", "true");
|
|
document.body.style.overflow = "";
|
|
}
|
|
|
|
window.openSearchDialog = openDialog;
|
|
window.closeSearchDialog = closeDialog;
|
|
|
|
if (mask) {
|
|
mask.addEventListener("click", function (e) {
|
|
if (e.target !== mask) return;
|
|
closeDialog();
|
|
});
|
|
}
|
|
|
|
document.addEventListener("keydown", function (e) {
|
|
if (!mask.classList.contains("is-open")) return;
|
|
if (e.key === "Escape") closeDialog();
|
|
});
|
|
|
|
// 移动端:点击头部搜索栏 → 打开搜索弹窗,而不是直接跳转
|
|
if (headerForm) {
|
|
headerForm.addEventListener("submit", function (e) {
|
|
if (!isMobile()) return;
|
|
e.preventDefault();
|
|
var v = headerInput ? headerInput.value : "";
|
|
openDialog(v);
|
|
});
|
|
|
|
headerForm.addEventListener("click", function (e) {
|
|
if (!isMobile()) return;
|
|
// 避免点到表单外或触发非预期行为
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
var v = headerInput ? headerInput.value : "";
|
|
openDialog(v);
|
|
});
|
|
}
|
|
|
|
// 提交时如果是空关键字,不跳转(避免触发接口报参数错误等情况)
|
|
if (form) {
|
|
form.addEventListener("submit", function (e) {
|
|
var q = input ? String(input.value || "").trim() : "";
|
|
if (!q) {
|
|
e.preventDefault();
|
|
if (input) input.focus();
|
|
}
|
|
});
|
|
}
|
|
})();
|