C#.MVC+JQuery1.9自定义下拉框控件
2014-01-27 17:54
337 查看
一组漂亮的CSS,加上一段功能强大的JS,加上前后分工明确的MVC,再加上我几天的打码时间,就蛋生了一个可扩展的下拉框控件:输入内容时自动查找下拉列表项、上下键回车选择、列表显示滚动条、下拉框选择后触发改变事件、附带Text值Value值(可扩展更多值)........
没时间整理了,直接贴代码上来,等过年有时间了再整了,到时候找个漂亮的皮肤换上去再贴截图给你们看。
(没用过VS.MVC的请按Alt+F4)
Controllers:
Controllers:
DDLTest.aspx:
comboBox.js
.CSS
没时间整理了,直接贴代码上来,等过年有时间了再整了,到时候找个漂亮的皮肤换上去再贴截图给你们看。
(没用过VS.MVC的请按Alt+F4)
Controllers:
namespace MvcJSCommon.Controllers { /// <summary> /// /// </summary> public static class HtmlExtensions { /// <summary> /// 自定义下拉框控件 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="htmlHelper"></param> /// <param name="name">控件名</param> /// <param name="source">列表源</param> /// <param name="exprValue">绑定值字段</param> /// <param name="exprText">绑定文本字段</param> /// <param name="defaultVal">默认值,可为null</param> /// <param name="htmlAttributes">html属性,可为null</param> /// <param name="edit">是否可编辑</param> /// <returns></returns> public static MvcHtmlString DropDownListCustom<T> (this HtmlHelper htmlHelper, string name, IEnumerable<T> source, Expression<Func<T, object>> exprValue , Expression<Func<T, object>> exprText, object defaultVal = null, object htmlAttributes = null, bool edit = false) { return MvcHtmlString.Create(DropDownListCustomHtml(name, source, exprValue, exprText, defaultVal, htmlAttributes, edit)); } /// <summary> /// 生成下拉html代码重载 /// </summary> /// <typeparam name="T">绑定实体类型</typeparam> /// <param name="name">Comobx的ID</param> /// <param name="source"></param> /// <param name="exprValue"></param> /// <param name="exprText"></param> /// <param name="defaultVal"></param> /// <param name="htmlAttributes"></param> /// <param name="edit"></param> /// <returns></returns> public static string DropDownListCustomHtml<T>(string name, IEnumerable<T> source, Expression<Func<T, object>> exprValue, Expression<Func<T, object>> exprText, object defaultVal = null, object htmlAttributes = null, bool edit = false) { List<SelectListItem> selectList = new List<SelectListItem>(); if (exprValue != null && exprText != null) { var handlerValue = exprValue.Compile(); var handlerText = exprText.Compile(); if (source == null) { source = new List<T>(); } foreach (var i in source) { var value = (handlerValue.Invoke(i) ?? new object()).ToString(); var text = (handlerText.Invoke(i) ?? new object()).ToString(); var selected = (defaultVal != null && defaultVal.ToString().Equals(value, StringComparison.OrdinalIgnoreCase)); selectList.Add(new SelectListItem() { Value = value, Text = text, Selected = selected }); } } return DropDownListCustomHtml(name, selectList, htmlAttributes, edit); } /// <summary> /// 生成下拉html代码 /// </summary> /// <param name="name"></param> /// <param name="selectList"></param> /// <param name="htmlAttributes">样式处理只能以下几个new {@classinput="xxx",@inputwidth="110",@classdropdiv="drop",@dropdivwidth="20",@classselectdiv="selectDiv",@selectdivheight="100"}</param> /// <returns></returns> private static string DropDownListCustomHtml(string name, IEnumerable<SelectListItem> selectList, object htmlAttributes, bool edit = false) { StringBuilder attrs = new StringBuilder(); #region 样式处理 string classTop = "select"; string width = "", height = ""; if (htmlAttributes != null) { var t = htmlAttributes.GetType(); foreach (var property in t.GetProperties()) { switch (property.Name.ToLower()) { case "class"://总的样式 classTop = property.GetValue(htmlAttributes, null).ToString(); break; case "width": //宽 width = property.GetValue(htmlAttributes, null).ToString(); break; case "height": //高 height = property.GetValue(htmlAttributes, null).ToString(); break; default: break; } } } #endregion StringBuilder sb = new StringBuilder(); string defaultText = string.Empty; string defaultValue = string.Empty; StringBuilder sbText = new StringBuilder(); if (!selectList.IsNullOrEmpty()) { defaultText = selectList.ElementAt(0).Text; defaultValue = selectList.ElementAt(0).Value; //是否有默认值 var model = from c in selectList where c.Selected == true select c; if (!model.IsNullOrEmpty()) { defaultText = model.ElementAt(0).Text; defaultValue = model.ElementAt(0).Value; } foreach (var item in selectList) { sbText.AppendFormat("<li itemvalue=\"{0}\">{1}</li>", item.Value, item.Text); } } if (!string.IsNullOrEmpty(width)) { width = string.Format("width:{0}px;", width); } if (!string.IsNullOrEmpty(height)) { height = string.Format("height:{0}px;", height); } sb.AppendFormat("<div id=\"divComBox_{0}\" class=\"{1}\" tabindex=\"0\" style=\"{2}{3}\">", name, classTop, width, height); sb.AppendFormat("<input type=\"text\" id=\"divComBox_Text_{0}\" value=\"{1}\" {2} />",name,defaultText,edit?"":"readonly=\"readonly\""); sb.AppendFormat("<input type=\"hidden\" id=\"divComBox_Value_{0}\" value=\"{1}\" />",name,defaultValue); sb.AppendFormat("<ul>{0}</ul>",sbText); sb.Append("</div>"); return sb.ToString(); } } } namespace System { public static class SystemEx { /// <summary> /// 判断一个List是否为空或者Count=0 /// </summary> /// <typeparam name="T">类型</typeparam> /// <param name="list">列表</param> /// <returns>是否为空</returns> public static bool IsNullOrEmpty<T>(this IEnumerable<T> list) { if (list == null) return true; if (list.Count() == 0) return true; return false; } } }
Controllers:
public ActionResult DDlTest() { ViewBag.Message = "下拉框控件-黑色样式"; List<TestInfo> list = new List<TestInfo>(); for (int i = 0; i < 50; i++) { list.Add(new TestInfo { UserName = "UserName" + i.ToString(), UserID = "UserID" + i.ToString(), UserSEX = "UserSEX" + i.ToString(), UserAddress = "UserAddress" + i.ToString() }); } ViewData["DDLList"] = list; return View(); }
public class TestInfo { public string UserName { get; set; } public string UserID { get; set; } public string UserSEX { get; set; } public string UserAddress { get; set; } }
DDLTest.aspx:
<script type="text/javascript"> $(document).ready(function () { CustomComBox.Bind('TestDDL'); //初始化控件,不然用不了 }); </script>
<div style="background: #222;padding:5px 5px 5px 5px;margin: 3px; text-align: right;" > <%=Html.DropDownListCustom("TestDDL", ViewData["DDLList"] as List<TestInfo>, c => c.UserID, c => c.UserName, null, new { @class = "SelectDDL" }, true)%> </div>
comboBox.js
//主控件点击事件 var funcOnClickComBox = function (objID) { var divComboBox = $(this); var txtComboBox = divComboBox.find(":text"); divComboBox.children("ul").toggle(0, function () { if ($(this).is(":visible")) { txtComboBox.focus(); } else { } }); } //初始化 var funcComBoxEventBind = function (objID) { //debugger var divComboBox = $("#divComBox_" + objID) var ulComboBox = divComboBox.find("ul"); var txtComboBox = divComboBox.find(":text"); var valueComboBox = divComboBox.find(":input[type='hidden']"); var liList = divComboBox.find("li"); var mouseInDiv = false; //主控件点击事件:显示下拉列表 divComboBox.bind("click", funcOnClickComBox); //设置内文本框宽度 txtComboBox.width(divComboBox.innerWidth() - 30 - 5); //设置下拉列表弹出的位置 ulComboBox.css("left", txtComboBox.position().left); ulComboBox.css("top", txtComboBox.position().top + txtComboBox.outerHeight()); ulComboBox.width(txtComboBox.outerWidth() - 2); //列表项点击事件 liList.each(function (i, n) { $(this).bind('click', function () { //清除所有选中 liList.attr({ "selected": false }); liList.removeClass("selected"); //设置点击项为当前选中项 $(this).attr({ "selected": true }); $(this).addClass("selected"); //取值赋值 txtComboBox.val($(this).text()); var oldValue = valueComboBox.val(); valueComboBox.val($(this).attr("itemValue")); if (oldValue != valueComboBox.val()) { txtComboBox.trigger('change'); } txtComboBox.focus(); }); }); var mouseinout = $("#mouseinout"); divComboBox.hover(function () { mouseInDiv = true; mouseinout.html("mouse In"); }, function () { mouseInDiv = false; mouseinout.html("mouse Out"); }); //控件失去焦点事件:隐藏下拉列表 txtComboBox.blur(function () { if (!mouseInDiv && ulComboBox.css("display") == "block") { ulComboBox.css("display", "none"); } }); divComboBox.blur(function () { if (!mouseInDiv && ulComboBox.css("display") == "block") { ulComboBox.css("display", "none"); } }); // //鼠标离开事件 若想要此功能则去掉注即可 // ulComboBox.mouseleave(function () { // if ($(this).css("display") == "block") { // $(this).css("display", "none"); // } // }); //回车事件 txtComboBox.bind('keydown', function () { //回车 if (event.keyCode == 13) { var queryselect = false; for (var i = 0; i < liList.length; i++) { if ($(liList[i]).attr("selected")) { //附值Text txtComboBox.val($(liList[i]).text()); //附值Value valueComboBox.val($(liList[i]).attr("itemvalue")); queryselect = true; break; } } if (queryselect == false) { if (ulComboBox.css("display") == "none") { ulComboBox.css("display", "block"); } } else { if (ulComboBox.css("display") == "block") { ulComboBox.css("display", "none"); } } } }); //按键输入事件 txtComboBox.bind('keyup', function () { //不处理回车事件 if (event.keyCode == 13) { return; } if (ulComboBox.css("display") == "none") { ulComboBox.css("display", "block"); } valueComboBox.val(""); //处理输入的内容自动找到下拉列表对应项 var retunobj = CustomEasyComBox.SelecValueEven(divComboBox, liList, ulComboBox, txtComboBox.val(), valueComboBox.val(), false); //上下键滚动列表项 if (event.keyCode == 38 || event.keyCode == 40) { liList.removeClass("selected"); liList.attr("selected", false); var indexitem = retunobj.index; //debugger switch (event.keyCode) { case 38: //向上38 indexitem = indexitem - 1; break; case 40: // 40向下 indexitem = indexitem + 1; break; default: } if (indexitem < 0) { indexitem = 0; } if (indexitem >= liList.length) { indexitem = liList.length - 1; } $(liList[indexitem]).attr({ "selected": true }); $(liList[indexitem]).addClass("selected"); //上下翻动时,列表滚动条跟着滚 CustomEasyComBox.ScrollList(ulComboBox, $(liList[indexitem])); txtComboBox.val($(liList[indexitem]).text()); valueComboBox.val($(liList[indexitem]).attr("itemvalue")); return; } }); }
//列表滚动 var funcScrollList = function (ulComboBox, liItem) { var liTop = liItem.position().top; //debugger var liHeight = liItem[0].offsetHeight; var maxULHeight = ulComboBox[0].offsetHeight; //debugger if (liTop + liHeight > maxULHeight) { ulComboBox.scrollTop(ulComboBox.scrollTop() + (liHeight > liTop + liHeight - maxULHeight ? liHeight : liTop + liHeight - maxULHeight)); } if (liTop < 0) { ulComboBox.scrollTop(ulComboBox.scrollTop() + liTop); } } //处理输入的内容自动找到下拉列表对应项 var funcSelecValueEven = function (divComboBox, liList, ulComboBox, idTxt, idValue, isValue) { //清除所有选中 liList.removeClass("selected"); liList.attr("selected", false); var returnobj = { index: -1, itemvalue: "", itemText: "" }; var scrollheight = 0; var selectValue = false; //判断按text查找还是按value查找 if (isValue == true) { if (idValue != "") { for (var i = 0; i < liList.length; i++) { scrollheight += $(liList[i]).height(); if ($(liList[i]).attr("itemvalue") == idValue) { $(liList[i]).attr({ "selected": true }); $(liList[i]).addClass("selected"); CustomEasyComBox.ScrollList(ulComboBox, $(liList[i])); returnobj.index = i; returnobj.itemText = $(liList[i]).text(); returnobj.itemvalue = idValue; selectValue = true; break; } } } } else { if (idTxt != "") { for (var i = 0; i < liList.length; i++) { scrollheight += $(liList[i]).height(); if ($(liList[i]).text().toUpperCase().indexOf(idTxt.toUpperCase()) >= 0) { $(liList[i]).attr({ "selected": true }); $(liList[i]).addClass("selected"); CustomEasyComBox.ScrollList(ulComboBox, $(liList[i])); returnobj.index = i; returnobj.itemText = $(liList[i]).text(); returnobj.itemvalue = $(liList[i]).attr("itemvalue"); selectValue = true; break; } } } } if (selectValue == false) { scrollheight = 0; } divComboBox.scrollTop(scrollheight - 35); return returnobj; } var CustomEasyComBox = { ComBoxEventBind: funcComBoxEventBind, OnClickComBox: funcOnClickComBox, ScrollList: funcScrollList, SelecValueEven: funcSelecValueEven }
.CSS
body { text-align: left; /*color: #c8c8c8;*/ font: 12px/20px Arial, Helvetica, sans-serif, SimSun; } * { margin: 0 auto; } /*下拉框外层DIV的样式*/ .SelectDDL { position: relative; display: inline-block; margin: 0 0 0 0; width: 150px; border: 1px solid #797979; text-align: left; vertical-align: top; color: #e0e0e0; cursor: pointer; padding: 0px; line-height: 30px; } /*输入框的样式(包含下拉箭头)*/ .SelectDDL input { font: 12px/20px Arial, Helvetica, sans-serif, SimSun; padding: 5px 30px 5px 5px; height: 20px; width: 115px; zoom: 1; background: url(../../images/sprite.gif) no-repeat; margin: 0px; background-position: right -40px; line-height: 20px; color: #e0e0e0; border-style: none; cursor: pointer; } /*输入框的焦点样式*/ .SelectDDL input:focus { border: none; } /*列表样式*/ .SelectDDL ul { display: none; position: absolute; top: 30px; left: -1px; width: 100%; min-height: 25px; _height: 25px; border: 1px solid #646464; background: #202020; line-height: 25px; margin: 0px; padding: 0px; border-spacing: 2px; border-color: gray; border-collapse: collapse; border-spacing: 0; overflow: auto; max-height : 320px !important; } /*列表项样式*/ .SelectDDL li { display: block; padding: 0 5px; background: #202020; zoom: 1; } /*列表项鼠标经过样式*/ .SelectDDL li:hover { background: #262626; color: #b93b26; } /*列表项选中时的样式*/ .SelectDDL li.selected { background: #262626; color: #b93b26; }
相关文章推荐
- jquery元素选择器集合
- jQuery 常见操作实现方式
- jquery json
- jquery的uploadify的用法小结
- 基于JQuery的Select级联
- (二)struts2- 2.3.15.3 spring3.2.4 mybatis-3.2.3 集成jquery-ui-1.10.3
- 15个jQuery代码片段
- 一款效果精致的 jQuery 多层滑出菜单插件
- 20款响应式jQuery插件
- jquery获得select option的值 和对select option的操作
- 怎样让jQuery和其它js库共存
- Js Jquery创建一个弹出层(当加载一个页面进弹出层时出现乱码)
- jquery选择器之属性过滤选择器详解
- jQuery实现动画效果的简单实例
- jQuery中bind与live的用法及区别小结
- jQuery自定义事件的简单实现代码
- jquery选择器之属性过滤选择器详解
- jquery选择器之内容过滤选择器详解
- jquery选择器之层级过滤选择器详解
- jquery选择器之基本过滤选择器详解