Html+css+js实战:百度搜索框样式实现

一、效果展示

二、代码实现

<!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">
    <title>百度搜索</title>
</head>

<body>
    <div id="box1" class="box1">
        <div class="image"><img src="../asset/bd_logo.jpeg" alt=""></div>
        <input type="text"><button>百度一下</button>
    </div>
</body>
<script>
    var box1 = document.getElementById("box1")
    var input = document.querySelector("input")
    input.onkeyup = function() {
        box1.setAttribute('class', 'box2')
    }
</script>

<style>
    /* 初始化全局样式 */
    
    * {
        margin: 0;
        padding: 0;
    }
    
    .box1 {
        width: 600px;
        height: 300px;
        margin: 250px auto;
        position: relative;
    }
    
    .box2 {
        width: 600px;
        height: 300px;
        margin: 0 0 0 180px;
        position: relative;
        padding-top: 40px;
    }
    
    .box1 input {
        width: 500px;
        height: 40px;
        box-sizing: border-box;
        text-indent: 10px;
        font-size: 16px;
    }
    
    .box2 input {
        width: 500px;
        height: 40px;
        box-sizing: border-box;
        text-indent: 10px;
        font-size: 16px;
    }
    
    button {
        width: 100px;
        height: 40px;
        box-sizing: border-box;
        background-color: #38f;
        border: none;
        color: white;
        font-size: 16px;
        position: absolute;
        left: 500px;
        /*聚焦样式 */
        cursor: pointer;
        border-radius: 3px;
    }
    
    button:hover {
        background-color: #2d78f4;
    }
    
    .box1 .image {
        position: absolute;
        top: -140px;
        left: 170px;
    }
    
    .box1 .image img {
        width: 270px;
        height: 130px;
    }
    
    .box2 .image {
        position: absolute;
        top: 18px;
        left: -170px;
    }
    
    .box2 .image img {
        width: 170px;
        height: 80px;
    }
</style>

</html>

三、涉及要点

1.动态为页面元素添加类

var box1 = document.getElementById("box1")
    var input = document.querySelector("input")
    input.onkeyup = function() {
        box1.setAttribute('class', 'box2')
    }

注意:

  1. 获取元素不能通过class来获取,否则在setAttribute的时候会报错
  2. input是输入框,onkeyup是在输入框输入内容时按键抬起时触发
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值