美文网首页
JS模拟placeholder属性

JS模拟placeholder属性

作者: 王远清orz | 来源:发表于2019-10-09 11:19 被阅读0次
    <input type="text" name="" id="txtSearch" value="请输入搜索内容">
    <input type="button" value="搜索" id="btnSearch">
    <script>
        // 搜索框获得焦点,文本框中文字消失,输入的文字颜色#333;  失焦如果文本框中无内容,则显示“请输入搜索内容”,并且颜色为#999;
        // 1.给搜索框文本注册事件
        var txtSearch = document.getElementById('txtSearch');
        // 2.搜索框获得焦点,文本框中文字消失,输入的文字颜色#333;
        txtSearch.onfocus = function () {
          if( this.value === '请输入搜索内容'){
            this.value = "";
            this.style.color = "#333";
          }
        }
        //3.失焦如果文本框中无内容,则显示“请输入搜索内容”,并且颜色为#999;
        txtSearch.onblur = function () {
          if (this.value.length === 0 || this.value === '请输入搜索内容') {
            this.value = "请输入搜索内容";
            this.style.color = "#999";
          }
        }
      </script>
    

    相关文章

      网友评论

          本文标题:JS模拟placeholder属性

          本文链接:https://www.haomeiwen.com/subject/wvwwpctx.html