文本框获得焦点和失去焦点

今天想介绍一下文本框获得焦点和失去焦点的两种方法:


第一种: html5

html5给表单文本框新增加了几个属性,比如:email,tel,number,time,required,autofocus,placeholder等等,这些属性给表单效果带来了极大的效果变化。

其中placeholder就是其中一个,它可以同时完成文本框获得焦点和失去焦点。必须保证input的value值为空, placeholder的内容就是我们在页面上看到的内容。

代码如下:

<input type="text" value="" placeholder="请输入内容" />


第二种: jQuery

原理:让表单的val值等于其title值。

代码如下:

<input type="text" value="" title="请输入内容" />


 1 <script type="text/javascript">
 2     $(function() {
 3         var $input = $("input");
 4         
 5         $input.each(function() {
 6             var $title = $(this).attr("title");
 7                     
 8             $(this).val($title);
 9                         
10             $(this).focus(function() {
11                 if($(this).val() === $title) {
12                     $(this).val('');
13                 }
14             })
15             
16             .blur(function() {
17                 if($(this).val() === "") {
18                     $(this).val($title);
19                 }
20             });
21         });
22     });
23 </script>
原文地址:https://www.cnblogs.com/gaoyubao/p/2398066.html