先看一下基于此做的小案例,核心就是那三行js,原理很简单,但是这个思路很棒
话不多说,上代码(粘贴可以直接使用),js部分href可以更改链接来切换不同的搜索引擎
html
<form onsubmit="return search()">
<input type="text" class="search" placeholder="想搜点啥" autocomplete="off" autofocus>
<button onclick="return search">搜索</button>
</form>
js部分
function search() {
if (document.querySelector(".search").value != "") {
window.location.href = "https://cn.bing.com/search?q=" + document.querySelector(".search").value;
document.querySelector(".search").value = "";
}
return false;
}
上面动图代码如下,核心就是上面的两端代码,只是加了一点样式而已,很简单
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>搜索框</title>
</head>
<style>
* {
margin: 0;
padding: 0;
}
.search-box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
border-radius: 25px;
height: 40px;
padding: 10px;
background-color: #CCC;
}
.search-box:hover>.search {
width: 200px;
padding: 0 6px;
}
.search-box:hover>.search-cli {
transform: rotateX(360deg);
transition: 0.8s;
}
.search-cli {
float: right;
width: 40px;
height: 40px;
border: none;
border-radius: 50%;
display: flex;
justify-content: center;
align-items: center;
transition: 0.4s;
background-color: #CCC;
}
.search {
border: none;
background: none;
outline: none;
float: left;
padding:0;
color: white;
font-size: 16px;
line-height: 40px;
transition: 0.4s;
width: 0;
}
img {
width: 100%;
height: auto;
}
</style>
<body>
<form class="search-box" onsubmit="return search()">
<input type="text" class="search" placeholder="想搜点啥" autocomplete="off" autofocus>
<button class="search-cli" onclick="return search">
<img src="./img/放大镜.svg" alt="">
</button>
</form>
</body>
<script>
function search() {
if (document.querySelector(".search").value != "") {
window.location.href = "https://cn.bing.com/search?q=" + document.querySelector(".search").value;
document.querySelector(".search").value = "";
}
return false;
}
</script>
</html>