我如何将搜索按钮固定在它所在的位置?



从下面的链接中可以看到,搜索按钮正在随着输入同时展开。当你点击图标时,它也在移动。

代码

const search = document.querySelector('.search')
const btn = document.querySelector('.btn')
const input = document.querySelector('.input')
btn.addEventListener('click', () => {
search.classList.toggle('active')
input.focus()
})
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap');
* {
box-sizing: border-box;
}
body {
background-image: linear-gradient(90deg, #7d5fff, #7158e2);
font-family: 'Roboto', sans-serif;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
}
.search {
position: relative;
height: 50px;
}
.search .input {
background-color: #fff;
border: 0;
font-size: 18px;
padding: 15px;
height: 50px;
width: 50px;
transition: width 0.3s ease;
}
.btn {
background-color: #fff;
border: 0;
cursor: pointer;
font-size: 24px;
position: absolute;
top: 0;
left: 0;
height: 50px;
width: 50px;
transition: transform .3s ease;
}
.btn:focus,
.input:focus {
outline: none;
}
.search.active .input {
width: 200px;
}
.search.active .btn {
transform: translateX(198px);
}
<!DOCTYPE html>
<html lang="en">
<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" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>
<link rel="stylesheet" href="style.css" />
<title>Hidden Search</title>
</head>
<body>
<div class="search">
<label>
<input type="text" class="input" placeholder="Search..." />
</label>
<button class="btn">
<i class="fas fa-search"></i>
</button>
</div>
<script src="app.js"></script>
</body>
</html>

但是我想把搜索按钮固定在右边,只把输入区域扩展到左边。我尝试了position:fixed属性,但它不起作用。你能帮我处理一下吗?

如果我理解正确的话,您根本不想翻译带有放大镜图标的按钮。但是,你有一个translateXcss属性,它将把它向右移动198px(正x方向)。

我将只对输入元素进行动画化,并对css类进行以下修改:

.search .input {
background-color: #fff;
border: 0;
font-size: 18px;
height: 50px;
/* Hide the input element by default by making it 0 width */
position: absolute;
padding: 0;
width: 0;
/* Animate both the width and left properties on css property change */
transition: width 0.3s ease, left 0.3s ease;
left: 0;
}
.search.active .input {
/* Set width and position when this class is active */
width: 200px;
left: -200px;
padding: 15px;
}
/* Remove any transforms for the search button */
/* .search.active .btn {
transform: translateX(198px);
} */

最新更新