javascript获得焦点 失去焦点 事件

获得焦点: onfocus

失去焦点: onblur

html

 <div class="search">
        <input type="text" value="请输入..." id="txt" />
        <button></button>
    </div>

css

 <style>
        input,
        button {
            border: 0 none;
            padding: 0;
        }
        .search {
            width: 258px;
            height: 40px;
            margin: 100px auto;
        }
        .search input {
            width: 208px;
            height: 40px;
            background: url(images/left.jpg) no-repeat;
            outline-style: none;
            padding-left: 8px;
            color: #ccc;
            float: left;
        }
        .search button {
            width: 40px;
            height: 42px;
            background: url(images/right.jpg) no-repeat;
            float: left;
            cursor: pointer;
        }
    </style>

js

 <script>
            window.onload = function(){
    
                var txt = document.getElementById("txt");
                txt.onfocus = function(){ //得到焦点
                    //alert("得到了焦点");
                    //什么时候该清空呢
                    //用户没有输入的时候,用户第一次使用的时候
                   // 如果 这里input 里面的文字 是 请输入...  说明用户没有用过,就应该清空
                    if(txt.value == "请输入..."  )
                    {
                        txt.value = "";
                        txt.style.color = "#333";
                    }
                }
                txt.onblur = function(){ //失去焦点
                    //alert("失去了焦点");
                    //什么时候再还原呢?
                    //input的值是 空的时候,我们再复原
                    if(txt.value == "")
                    {
                        txt.value = "请输入...";
                        txt.style.color = "#ccc";
                    }
                }
            }
        </script>
    
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 作者 陈思琪 三年级 她将裙摆放到一边, 弯下腰行鞠躬礼。 她将头发摆到耳旁, 轻轻地微笑。 她喷的香水味儿, 慢...
    helenxxf阅读 174评论 0 0
  • JS实现一些经典算法:1,基于填坑思想的快排算法2,十进制转十六进制 NODEJS抓包的坑 利用request模块...
    MatrixFK阅读 165评论 0 0
  • 今天同学带儿媳妇,听说有同学们安排的闹喜游街,很久不爱凑热闹的我却按捺不住好奇心,早早的赶到现场,最终还是迟了半步...
    若水_086阅读 1,638评论 2 9
  • 现在人人都在辛苦工作,以求升职加薪,然而无论赚多少,总感觉不够花,因为随着工资的上涨,需求也在不断增加。有时候,我...
    沐风简书阅读 650评论 0 0
  • 12月25日 今天是圣诞节,也是我出院的日子。原本和老公商量好的是明天出院的,但是老公的一个电话打破了我们原有的计...
    钱塘潮阅读 934评论 0 0