仿某东的搜索框初级版

首先需要获取焦点事件 onfocus和失去焦点事件 onblur

 下面是代码环节:

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8" />
    <style type="text/css">
        input{
            color: #999;
            outline:2px solid red;
            outline-offset: 2px;
            border: none;
            display: block;
            margin:50px auto;
        }
    </style>
    <title>Document</title>
</head>
<body>
    
    <input type="text" name="" id="" value="手机" />
    <script type="text/javascript">
//        获取元素
        var ipt = document.getElementsByTagName("input");
//        注册事件 获取焦点事件 onfocus
        ipt[0].onfocus = function(){            
//            alert("得到了焦点");实验一下能不能得到焦点
            if(ipt[0].value === "手机"){
            ipt[0].value = ""
        }
        
        ipt[0].setAttribute("style","color: #333;");
        }
//        注册事件 失去焦点事件 onblur
        ipt[0].onblur = function(){
//            alert("失去焦点");实验一下能不能失去焦点
            if(ipt[0].value === ""){
            ipt[0].value = "手机"
        }
            ipt[0].setAttribute("style","color: #999;");
        }
    </script>
</body>
</html>

某东效果图

猜你喜欢

转载自www.cnblogs.com/niuyaomin/p/11824012.html