在开发Web应用程序中经常需要用户在文本框输入信息,为了提高程序人性化设置以及用户体验效果常常需要在文本框中显示灰色字体辅助用户输入
如:
"文本不能为空"是这样实现的,博主进行了适当的封装,建立简单MVC.NET应用程序的Demo引用Jquery的包,html代码
1 @{
2 ViewBag.Title = "Index";
3 }
4 <script src="~/Scripts/jquery-2.1.4.min.js"></script>
5 <script src="~/Scripts/jquery-textboxhelper.js"></script>
6 <script>
7 $(function () {
8 $('#button').click(function () {
9 var getTextValue = $('#text').val();
10 if (getTextValue == '')
11 {
12 alert("文本为空!");
13 return;
14 }
15 alert(getTextValue);
16 })
17
18
19 $("#text").TextTip("文本不能为空");
20
21 })
22 </script>
23
24 <input id="text" type="text" />
25 <input id="button" type="button" value="输出文本值"/>
关键在于自定义js文件jquery-textboxhelper.js
1 (function ($) {
2 var defaults = {
3 fontColor: '#ccc',
4 tipContent: '请输入内容',
5 focusColor: 'black'
6 };
7
8 $.fn.TextTip = function (tipContent, fontColor) {
9 var options = {};
10 $.extend(options, defaults)
11
12 if (typeof tipContent == 'string') {
13 options.tipContent = tipContent
14 }
15
16 if (typeof fontColor == 'string') {
17 options.fontColor = fontColor
18 }
19
20 this.each(function () {
21 $(this).bind({
22 focus: function () {
23 if (this.value == options.tipContent) {
24 this.value = "";
25 this.style.color = options.focusColor
26 }
27
28 }, blur: function () {
29 if (this.value == "") {
30 this.value = options.tipContent;
31 this.style.color = options.fontColor
32 }
33 }
34 })
35
36 $(this).val(options.tipContent).css('color', options.fontColor);
37 $(this).blur();
38 })
39 }
40 })(jQuery);
演示: