解决默写浏览器中点击input输入框时,placeholder的值不消失的方法
html中,placeholder作为input的一个属性,起到了在输入框中占位并提示的作用。
但是有一些浏览器,如chrome,当鼠标点击输入框时,placeholder的值不消失,只有输入数据才消失,会使前端用户体验大打折扣。
我们要实现的效果:
点击前
点击后
关键是js代码:
$(function(){ var text; // 全局变量用于保存文本框的内容 $("input").focus(function() { text = $(this).attr("placeholder"); $(this).attr("placeholder",""); }).blur(function() { $(this).attr("placeholder",text); }); })
完整实现代码test.html
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <div class="box"> <span>解决默写浏览器中点击input输入框时,placeholder的值不消失的方法</span> <div class="content"> <input type="text" name="name" placeholder="请输入姓名"/> <input type="text" name="sex" placeholder="请输入性别"/> <input type="text" name="date" placeholder="请输入日期"/> </div> </div> <style> div.box{300px;padding:20px;margin:20px;border:4px dashed #ccc;} div.box span{color:#999;font-style:italic;} div.content{250px;margin:10px 0;padding:20px;border:2px solid #ff6666;} input[type='text']{200px;height:35px;padding:5px 10px;margin:5px 0;border:1px solid #ff9966;} </style> <script> $(function(){ var text; // 全局变量用于保存文本框的内容 $("input:text").focus(function() { text = $(this).attr("placeholder"); $(this).attr("placeholder",""); }).blur(function() { $(this).attr("placeholder",text); }); }) </script>
当然还有一个最简单的实现方法,效果同上
就是在DOM中写死 (但是不建议这样,因为这样做的耦合性太高了,而且当输入框很多的时候,就要写很多个啊)
<input type="text" name="name" placeholder="请输入" onfocus="this.placeholder=''" onblur="this.placeholder='请输入'"/>
点击前
点击后
但是有一些浏览器,如chrome,当鼠标点击输入框时,placeholder的值不消失,只有输入数据才消失,会使前端用户体验大打折扣。
我们要实现的效果:
点击前
点击后
关键是js代码:
$(function(){ var text; // 全局变量用于保存文本框的内容 $("input").focus(function() { text = $(this).attr("placeholder"); $(this).attr("placeholder",""); }).blur(function() { $(this).attr("placeholder",text); }); })
完整实现代码test.html
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <div class="box"> <span>解决默写浏览器中点击input输入框时,placeholder的值不消失的方法</span> <div class="content"> <input type="text" name="name" placeholder="请输入姓名"/> <input type="text" name="sex" placeholder="请输入性别"/> <input type="text" name="date" placeholder="请输入日期"/> </div> </div> <style> div.box{300px;padding:20px;margin:20px;border:4px dashed #ccc;} div.box span{color:#999;font-style:italic;} div.content{250px;margin:10px 0;padding:20px;border:2px solid #ff6666;} input[type='text']{200px;height:35px;padding:5px 10px;margin:5px 0;border:1px solid #ff9966;} </style> <script> $(function(){ var text; // 全局变量用于保存文本框的内容 $("input:text").focus(function() { text = $(this).attr("placeholder"); $(this).attr("placeholder",""); }).blur(function() { $(this).attr("placeholder",text); }); }) </script>
当然还有一个最简单的实现方法,效果同上
就是在DOM中写死 (但是不建议这样,因为这样做的耦合性太高了,而且当输入框很多的时候,就要写很多个啊)
<input type="text" name="name" placeholder="请输入" onfocus="this.placeholder=''" onblur="this.placeholder='请输入'"/>
点击前
点击后