75 lines
1.9 KiB
JavaScript
75 lines
1.9 KiB
JavaScript
// ============================================
|
|
// 百度搜索工具 - 核心逻辑
|
|
// ============================================
|
|
|
|
// 百度搜索 URL 前缀
|
|
const SEARCH_URL = 'https://www.baidu.com/s?wd=';
|
|
|
|
// DOM 元素
|
|
const searchInput = document.getElementById('searchInput');
|
|
const searchBtn = document.getElementById('searchBtn');
|
|
const hotTags = document.querySelectorAll('.hot-tag');
|
|
|
|
/**
|
|
* 执行搜索:打开百度搜索结果页
|
|
* @param {string} keyword - 搜索关键词
|
|
*/
|
|
function doSearch(keyword) {
|
|
const trimmed = (keyword || '').trim();
|
|
if (!trimmed) {
|
|
alert('请输入搜索关键词');
|
|
searchInput.focus();
|
|
return;
|
|
}
|
|
|
|
// 使用 encodeURIComponent 编码中文和特殊字符
|
|
const url = SEARCH_URL + encodeURIComponent(trimmed);
|
|
|
|
// 在新标签页打开搜索结果
|
|
window.open(url, '_blank', 'noopener,noreferrer');
|
|
}
|
|
|
|
/**
|
|
* 从当前输入框获取关键词并搜索
|
|
*/
|
|
function searchFromInput() {
|
|
doSearch(searchInput.value);
|
|
}
|
|
|
|
// ============================================
|
|
// 事件绑定
|
|
// ============================================
|
|
|
|
// 点击搜索按钮
|
|
searchBtn.addEventListener('click', searchFromInput);
|
|
|
|
// 输入框按回车键
|
|
searchInput.addEventListener('keydown', (e) => {
|
|
if (e.key === 'Enter') {
|
|
searchFromInput();
|
|
}
|
|
});
|
|
|
|
// 热门搜索标签点击
|
|
hotTags.forEach((tag) => {
|
|
tag.addEventListener('click', () => {
|
|
const word = tag.dataset.word;
|
|
searchInput.value = word;
|
|
doSearch(word);
|
|
});
|
|
});
|
|
|
|
// ============================================
|
|
// 支持从 URL 参数获取查询词(如 ?q=关键词)
|
|
// 用于浏览器扩展或外部调用
|
|
// ============================================
|
|
(function initFromQuery() {
|
|
const params = new URLSearchParams(window.location.search);
|
|
const q = params.get('q');
|
|
if (q) {
|
|
searchInput.value = q;
|
|
// 自动聚焦但不自动搜索,交给用户确认
|
|
searchInput.focus();
|
|
}
|
|
})();
|