input框失焦时文字消失,聚焦时文字出现

Posted on 2021-02-03 15:13  猫头唔食鱼  阅读(252)  评论(0编辑  收藏  举报
<!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>
</head>
<style>
    input{
        color: #ccc;
    }
</style>
<body>
    
    <input type="text" id="input" value="百度几下你都不知道">
    <script>
        var inputValue = '百度几下你都不知道'
        document.getElementById("input").onfocus = function(){
              if(this.value == inputValue){
                  this.value =  ''
              } 
        }

        document.getElementById("input").onblur = function(){
              this.value === '' ?  this.value = inputValue : this.value = this.value
        }

        document.getElementById("input").oninput = function(){
               this.style.color = '#000'
        }
    </script>
</body>
</html>

效果: