写一个搜索框,聚焦时搜索框向左拉长并有动画效果

要实现一个搜索框,当聚焦时向左拉长并有动画效果,你可以使用HTML、CSS和JavaScript。下面是一个简单的示例:

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Search Box Animation</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="search-container">
        <input type="text" id="search-input" class="search-input" placeholder="Search...">
    </div>
    <script src="script.js"></script>
</body>
</html>

CSS (styles.css)

body {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #f5f5f5;
}

.search-container {
    position: relative;
    width: 200px;
    transition: width 0.3s ease;
}

.search-input {
    width: 100%;
    padding: 10px;
    border: none;
    outline: none;
    background-color: #fff;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.search-input:focus {
    border: none;
    outline: none;
}

.search-input:focus + .search-container {
    width: 300px; /* Adjust this value to change the width when focused */
}

注意:在上面的CSS中,我使用了.search-input:focus + .search-container选择器来尝试在输入框聚焦时改变容器的宽度。但是,由于CSS的局限性,这种“+”选择器只能用于选择紧接在前面的元素之后的元素。因此,在实际应用中,你可能需要使用JavaScript来实现这个功能。

JavaScript (可选,用于更复杂的场景) (script.js)

如果你想要更多的控制或者要处理更复杂的布局,你可以使用JavaScript来监听输入框的focusblur事件。

document.addEventListener('DOMContentLoaded', function() {
    var searchInput = document.getElementById('search-input');
    var searchContainer = document.querySelector('.search-container');
    
    searchInput.addEventListener('focus', function() {
        searchContainer.style.width = '300px'; // Adjust this value to change the width when focused
    });
    
    searchInput.addEventListener('blur', function() {
        searchContainer.style.width = '200px'; // Reset to original width when blurred
    });
});

在这个JavaScript示例中,当输入框获得焦点时,容器的宽度会增加到300px,当输入框失去焦点时,容器的宽度会重置为200px。你可以根据需要调整这些值。

posted @   王铁柱6  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示