You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript实现类谷歌搜索输入框并跳转谷歌搜索

实现谷歌搜索跳转的输入框方案

核心思路

监听输入框的回车事件,获取输入内容后拼接成谷歌搜索的URL,跳转至该地址完成搜索。

完整实现代码

HTML(保留你的原有输入框,可按需添加搜索按钮)

<input class="finder" type="search" placeholder="Search in Google">
<!-- 可选:添加搜索按钮 -->
<button class="search-btn">搜索</button>

JavaScript 实现

// 获取输入框元素
const searchInput = document.querySelector('.finder');
// 可选:获取搜索按钮
const searchBtn = document.querySelector('.search-btn');

// 定义搜索跳转函数
function goToGoogleSearch() {
  const searchText = searchInput.value.trim();
  // 如果输入为空,不执行跳转
  if (!searchText) return;
  // 对搜索内容进行URL编码,避免特殊字符问题
  const encodedText = encodeURIComponent(searchText);
  // 拼接谷歌搜索URL并跳转
  window.location.href = `https://www.google.com/search?q=${encodedText}`;
}

// 监听输入框的回车事件
searchInput.addEventListener('keydown', (e) => {
  if (e.key === 'Enter') {
    goToGoogleSearch();
  }
});

// 可选:监听搜索按钮的点击事件
if (searchBtn) {
  searchBtn.addEventListener('click', goToGoogleSearch);
}

关键细节说明

  • 使用encodeURIComponent()对搜索内容编码,确保空格、特殊字符等能被正确识别
  • 先对输入内容做trim()处理,避免空内容或纯空格的无效搜索
  • 同时支持回车触发和按钮点击触发两种交互方式,可根据需求选择使用

内容的提问来源于stack exchange,提问作者Ustllys

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 23:11:14