最近做项目的时候,遇到一个对文本框这样的需求,此文本框既可以编辑,也可以点击按钮弹出选择。
废话不多说,直接上代码哈,第一个独立完成一个插件,还是有那么点小激动的。
虽然可以不适应项目的需求,当自己写着玩吧~~~
// JavaScript Document /* Author : Li zheng Date : 2012/01/30 Function : 对文本框适应可以选择和删除,也可以编辑 */ ;(function($){ $.fn.myInput = function(settings){ /*默认图标样式,用户可以在调用插件的时候修改默认值 icon_Select: 选择图标的class icon_Delete: 删除图标的class */ var defaults = { icon_Select: "icon_sel_sin_people", icon_Delete: "icon_delete" } var option = $.extend({},defaults,settings); //限定只有文本框可以使用本插件 var This = this.filter(":input[type=text]"); //文本框父级相对定位 This.parent().css("position","relative"); //创建选择和删除的图标 var iconSelect = $("<span id='icon_select' style='position: absolute; display:none;'></span>"); var iconDelete = $("<span id='icon_delete' style='position: absolute; display:none;'></span>"); //确定图标的样式并将图标添加到body iconSelect.addClass(option.icon_Select).appendTo("body"); iconDelete.addClass(option.icon_Delete).appendTo("body"); //文本框鼠标移入事件 This.mouseover(function(ev){ var objthis = $(this); //定位 var btnTop = objthis.offset().top; btnTop += parseInt(objthis.css("padding-top")); btnTop += parseInt(objthis.css("border-top-width")); btnTop += objthis.height()/2; btnTop -= 9; var btnLeft = objthis.offset().left; btnLeft += parseInt(objthis.css("padding-left")); btnLeft += parseInt(objthis.css("border-left-width")); btnLeft += objthis.width(); btnLeft -= 16; //console.log("left: "+btnLeft+", top: "+ btnTop); iconSelect.css({top: btnTop + "px",left:btnLeft + "px"}); iconDelete.css({top: btnTop + "px",left:btnLeft + "px"}); if(This.val()==""){ iconSelect.show(); iconDelete.hide(); } else{ iconSelect.hide(); iconDelete.show(); } }); //选择图标单击事件 iconSelect.bind("click",function(){ window.open("http://www.baidu.com","baidu","width=600,height=900"); }); //删除图标单击事件 iconDelete.bind("click",function(){ //console.log("iconDelete clicked"); This.val(""); }); //文本框出入事件 This.mouseout(function(ev){ if(ev.toElement.id=="icon_select"){iconSelect.show();} else if(ev.toElement.id=="icon_delete"){iconDelete.show();} else{ iconSelect.hide(); iconDelete.hide(); } }); //返回This,使插件方法可链 return This; } })(jQuery);
下面是页面对插件的调用
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>脚本测试</title> <link type="text/css" rel="stylesheet" href="style/library_1.1.css"> <link type="text/css" rel="stylesheet" href="style/base_control_1.1.css" /> <script type="text/javascript" src="script/jquery-1.7.2.min.js"></script> <script type="text/javascript" src="script/jquery.myInput.js"></script> <script type="text/javascript"> $(function(){ //测试myInput插件,并确认其可链性 $("input").myInput({ //icon_Select:"icon_sel_mul_people", icon_Delete:"icon_delete2" }).css({"background":"#eee","border":"solid 2px #ccc"}); }) </script> </head> <body> <input type="text" style="200px;height:30px;margin:20px auto;" /> </body> </html>
有兴趣的可以一起研究一下哈。