HTML中location.replace()跳转失效,求Google搜索跳转修复方案
问题修复方案
你的代码存在几个关键问题,导致location.replace()无法生效,以下是具体修复点和完整代码:
核心问题分析
- 无效嵌套按钮结构:HTML不允许
<button>标签嵌套另一个<button>,这种错误结构会导致点击事件混乱,浏览器会自动修正DOM,让你的redirect()函数无法正确触发。 - 表单默认提交行为:按钮默认类型为
submit,点击后会触发表单的默认提交动作(跳转到当前页面),直接覆盖了你写的跳转逻辑。 - 换行标签破坏布局:输入框后的
<br>会打乱flex布局结构,导致搜索框和按钮排版异常。
修复步骤
- 移除嵌套的
<button>,将点击事件绑定到外层按钮上 - 给按钮添加
type="button",阻止默认表单提交行为 - 删除输入框后的
<br>,保证flex布局正常工作 - 新增回车触发跳转的逻辑,提升用户体验
- 用
encodeURIComponent()处理搜索关键词,避免特殊字符导致跳转错误
修复后的完整代码
HTML代码
<!DOCTYPE html> <html lang="en" > <head> <meta charset="UTF-8"> <title>Google Search Jump</title> <link rel="stylesheet" href="./style.css"> </head> <body> <div class="search-bar"> <form class="search"> <input type="text" id="input" name="input" placeholder="Type here..."> <button type="button" onclick="redirect()" class="fas fa-search"></button> </form> </div> <script> function redirect() { let input = document.querySelector('#input').value.trim(); if (input) { location.replace(`https://www.google.com/search?q=${encodeURIComponent(input)}`); } } // 回车触发搜索 document.querySelector('#input').addEventListener('keydown', function(e) { if (e.key === 'Enter') { redirect(); } }); </script> </body> </html>
CSS代码(优化布局适配)
@import url("https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"); * { box-sizing: border-box; padding: 0; margin: 0; } button { cursor: pointer; transition: 1s ease; font-family: inherit; } html { color-scheme: dark; } body { background-color: #202124; font-family: "Poppins", sans-serif; display: flex; justify-content: center; align-items: center; min-height: 100vh; /* 让搜索框垂直水平居中 */ } .search-bar { max-width: 400px; width: 100%; } form.search { display: flex; width: min(90%, 25rem); border: 2px solid grey; border-radius: 25px; background-color: #202124; overflow: hidden; } form.search > * { padding: 0.8em 1em; border: none; background-color: transparent; font-size: 1.2rem; } form.search > :is(:focus, :focus-visible, :active){ outline: none; } form.search input { min-width: 0; flex: 1; } form.search button i { transition: inherit; } form.search button:hover i { scale: 1.2; }
内容的提问来源于stack exchange,提问作者Vedant Jain
相关产品推荐
相关产品推荐

