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>Document</title>
    <style>
        input {
     
     
            color: #999;
            outline: none;
        }
    </style>
</head>

<body>
    <input type="text" value="手机">
    <script>
        var input = document.querySelector('input'); //获取元素
        input.onfocus = function() {
     
      //获取焦点
            if (this.value == '手机') {
     
     
                console.log('获取焦点');
                this.value = ''; //清空默认value
            }
            this.style.color = '#333';
        }
        input.onblur = function() {
     
      //失去焦点  
            if (this.value == '') {
     
      //如果value 为空   则恢复‘手机’ 不为空则不执行
                console.log('失去焦点');
                this.value = '手机';
                this.style.color = '#999'
            }

        }
    </script>
</body>

</html>

猜你喜欢

转载自blog.csdn.net/llt299022/article/details/113727974