工作中需要一個樹形下拉框。項目裡的樹形結構本來用的是 zTree,於是先在網上找方案,效果都不太理想;後來試了 easyui 的 comboTree,外觀確實好看,但和整體的 bootstrap 風格有點不搭。兩種方式都記下來,以後備用。
思路是普通 input 作為觸發器,下面藏一個絕對定位的容器放 ul,點擊 input 時滑出,點擊頁面其他位置時收起。
前端代碼:
<div class="form-group">
<label>點擊事件:</label>
<input id="selectActionType" class="form-control"
onfocus="showActionTypeTree()"
onclick="showActionTypeTree()"
readonly="readonly"
style="border-radius:5px;background-color: white;cursor: default;" />
<input type="hidden" name="actionTypeId" id="actionTypeId" />
<div id="actionTreeContent" class="menuContent"
style="border-radius:5px;display: none; z-index:9999;
position: absolute; border: 1px #CCC solid; background-color:#f9f9f9;">
<ul id="actionTypeTree" class="ztree"
style="margin-top:0;height: 200px;overflow: auto"></ul>
</div>
</div>
js 代碼:
/*
* 點擊事件下拉樹的配置
*/
var actionTypeSetting = {
view: {
dblClickExpand: true,
showIcon: false,
fontCss: { 'font-weight': '400', 'font-size': '20px' }
},
data: {
key: { name: 'text', children: 'children' },
simpleData: { enable: true }
},
callback: {
onClick: actionTypeOnClick
}
};
/*
* 節點點擊回調:把 id 與名稱分別寫入 input 和 hidden
*/
function actionTypeOnClick(e, treeId, treeNode) {
$('#actionTypeId').val(treeNode.id);
$('#selectActionType').val(treeNode.text);
}
/*
* 初始化點擊事件類型
*/
function initActionType() {
$.ajax({
async: false,
cache: false,
type: 'POST',
dataType: 'json',
url: localStorage.getItem('adminPath') + '/touch/typeTable/getActionList?businessTypeId=2',
error: function () {
alert('請求失敗');
},
success: function (data) {
$.fn.zTree.init($('#actionTypeTree'), actionTypeSetting, data);
}
});
}
/*
* 展示點擊事件下拉樹
*/
function showActionTypeTree() {
$.ajax({
url: localStorage.getItem('adminPath') + '/touch/typeTable/getActionList?businessTypeId=2',
type: 'POST',
dataType: 'json',
async: false,
success: function (data) {
$.fn.zTree.init($('#actionTypeTree'), actionTypeSetting, data);
var deptObj = $('#selectActionType');
var deptOffset = $('#selectActionType').offset();
$('#actionTreeContent').css({
left: deptOffset.left - 26 + 'px',
top: deptOffset.top + 'px'
}).slideDown('fast');
$('#actionTypeTree').css({ width: deptObj.outerWidth() + 'px' });
// 回顯已選中節點
var zTree = $.fn.zTree.getZTreeObj('actionTypeTree');
var node = zTree.getNodeByParam('id', $('#actionTypeId').val(), null);
zTree.selectNode(node);
// 綁定全局點擊,用於點擊外部收起
$('body').bind('mousedown', onBodyDownByActionType);
}
});
}
/*
* Body 鼠標按下事件回調
*/
function onBodyDownByActionType(event) {
if (event.target.id.indexOf('switch') == -1) {
hideActionTypeMenu();
}
}
/*
* 隱藏點擊事件 Tree
*/
function hideActionTypeMenu() {
$('#actionTreeContent').fadeOut('fast');
$('body').unbind('mousedown', onBodyDownByActionType);
}
這套寫法的優點是完全可控,樣式、位置、交互都能按設計稿微調,和 bootstrap 的表單風格容易統一。缺點也明顯:定位靠手算 offset、收起靠全局 mousedown 監聽、每次展開都重新請求數據,代碼量和維護成本都不低。另外 async: false 會阻塞主線程,同步 ajax 在現代前端實踐裡應避免,改為先請求拿到數據緩存、再打開面板會更好。
前端代碼:
<div class="form-group"> <label>點擊事件:</label> <input id="actionTypeId2" name="actionTypeId2" class="form-control" /> </div>
js 代碼:
$('#actionTypeId2').combotree({
url: localStorage.getItem('adminPath') + '/touch/typeTable/getActionList?businessTypeId=2',
textField: 'name',
onClick: function (node) {
$('#actionTypeId').val(node.id);
},
onSelect: function (node) {
/**
* 選中節點時展開它,同時收起其他已展開的兄弟節點
*/
if (node.state == 'closed') {
$(this).tree('expand', node.target);
} else {
var isLeaf = $(this).tree('isLeaf', node.target);
if (!isLeaf) {
$(this).tree('collapse', node.target);
}
}
}
});
代碼量對比很懸殊:一個 url 加兩個回調就搞定了。定位、滾動、鍵盤操作、點擊外部收起這些細節,combotree 內部都處理好了。
position: absolute 配合容器 position: relative,避免手算 offset;同時去掉 async: false。一個通用建議:無論用哪種,選中值建議同時維護「顯示文本」和「隱藏 id」兩份狀態。只存 id 的話,回顯時還要反查名稱;只存名稱的話,同名節點會出歧義。上面 zTree 版本用 input + hidden input 的雙字段設計,正是這個道理。