(function(){
const inputId = 'searchInput'; // 你的搜索框 ID
const cache = {}; // 5 秒内存缓存
let timer = null;
let card = null; // 当前卡片引用
/* 创建卡片 DOM */
function createCard() {
if (card) return card;
const box = document.querySelector('.search-box');
if (!box) return;
card = document.createElement('div');
card.className = 'mdui-card';
card.style.marginTop = '4px';
card.innerHTML = '
';
box.parentNode.insertBefore(card, box.nextSibling); // 紧挨 search-box 下方
return card;
}
/* 销毁卡片 */
function removeCard() {
if (card) { card.remove(); card = null; }
}
/* 拉取 Bing 补全 */
function fetchSuggest(q) {
if (cache[q]) return fillCard(cache[q]);
const script = document.createElement('script');
const cb = 'bingSuggest' + Date.now();
window[cb] = function (data) {
delete window[cb]; script.remove();
const list = data.AS.Results.reduce((a, b) => a.concat(b.Suggests.map(s => s.Txt)), []);
cache[q] = list;
fillCard(list);
setTimeout(() => delete cache[q], 5000);
};
script.src = `https://api.bing.com/qsonhs.aspx?type=cb&cb=${cb}&q=${encodeURIComponent(q)}`;
document.head.appendChild(script);
}
/* 渲染列表 */
function fillCard(list) {
if (!list.length) return removeCard();
const ul = createCard().querySelector('#suggestList');
ul.innerHTML = '';
list.forEach(txt => {
const li = document.createElement('li');
li.className = 'mdui-list-item mdui-ripple';
li.textContent = txt;
li.tabIndex = 0;
li.onclick = () => jump(txt);
li.onkeydown = e => { if (e.key === 'Enter') jump(txt); };
ul.appendChild(li);
});
}
/* 跳转搜索 */
function jump(q) {
location.href = '?q=' + encodeURIComponent(q);
}
/* 防抖输入 */
const input = document.getElementById(inputId);
input.addEventListener('input', () => {
clearTimeout(timer);
const v = input.value.trim();
if (!v) return removeCard();
timer = setTimeout(() => fetchSuggest(v), 200);
});
/* 失焦 300 ms 后销毁卡片(保留点击时间) */
input.addEventListener('blur', () => setTimeout(removeCard, 300));
})();