Dtree 添加 checkbox 复选框
一:目标
要实现用一个树形结构的展示数据,每个节点(除了根节点)前有一个checkbox,同时,点击父节点,则子节点全选或者全不选,当选中了全部子节点,父节点选中;如下图所示:
注:本人把显示图标改成了false(个人觉得不好看),想用图标的话可以不用修改源文件,
useIcons : false// 想用图标,值为true
二:准备工作
1. dtree 的 js css等文件可以去官网上下载:http://destroydrop.com/javascripts/tree/
2.由于本人对js文件做出了修改,其中用到了jquery的选择器,所以引入一个jquery的js文件
三:详细步骤
1.如果要想将dtree引入到java的web项目中,请首先将js文件中的 function dTree(objName) 下的this.icon 下所有的图片路径修改成自己项目可以访问到的图片路径
1 this.icon = { 2 3 root : '/dtree/img/base.gif', 4 5 folder : '/dtree/img/folder.gif', 6 7 folderOpen : '/dtree/img/folderopen.gif', 8 9 node : '/dtree/img/page.gif', 10 11 empty : '/dtree/img/empty.gif', 12 13 line : '/dtree/img/line.gif', 14 15 join : '/dtree/img/join.gif', 16 17 joinBottom : '/dtree/img/joinbottom.gif', 18 19 plus : '/dtree/img/plus.gif', 20 21 plusBottom : '/dtree/img/plusbottom.gif', 22 23 minus : '/dtree/img/minus.gif', 24 25 minusBottom : '/dtree/img/minusbottom.gif', 26 27 nlPlus : '/dtree/img/nolines_plus.gif', 28 29 nlMinus : '/dtree/img/nolines_minus.gif' 30 31 };
View Code
2.在 function dTree(objName) 下this.config最后加入一个属性 userCheckbox,默认值为 true
1 this.config = { 2 3 target : null, 4 5 folderLinks : true, 6 7 useSelection : true, 8 9 useCookies : true, 10 11 useLines : true, 12 13 useIcons : false,//我给改了,不想让显示图标,太丑了 0.0 想要的话,改成true 14 15 useStatusText : false, 16 17 closeSameLevel : false, 18 19 inOrder : false, 20 21 useCheckbox : true //新加的 22 23 }
View Code
3.在 dTree.prototype.node = function(node, nodeId)下 if (this.config.useIcons) {} 结束之后加入以下代码,把checkbox加入进去,(checkbox做了美化,最后修改css文件)
1 if(this.config.useCheckbox == true && node.id != 0){ 2 str += '<label class="demo--label">' 3 + '<input type="checkbox" class="demo--radio" id="' + node.pid+ '_' + node.id 4 + '" onclick="javascript:' + this.obj + '.cc(' + node.id 5 + ',' + node.pid + ')"/>' 6 + '<span class="demo--checkbox demo--radioInput"></span>' 7 + '</label>'; 8 }
View Code
4. 在js文件的任意位置加入以下几个函数,为了实现父级子级 checkbox选中事件,代码中有详细注释,这里不做过多说明
1 .demo--label{display:inline-block} 2 .demo--radio{display:none} 3 .demo--radioInput{background-color:#fff;border:1px solid rgba(0,0,0,0.15);border-radius:100%;display:inline-block;height:13px;margin-right:5px;margin-top:-1px;vertical-align:middle;width:13px;line-height:1} 4 .demo--radio:checked + .demo--radioInput:after{background-color:#57ad68;border-radius:100%;content:"";display:inline-block;height:9px;margin:2px;width:9px} 5 .demo--checkbox.demo--radioInput,.demo--radio:checked + .demo--checkbox.demo--radioInput:after{border-radius:0}
View Code
四:说明
至此应该是结束了,如果按照步骤不能实现,请留言评论,咱们可以互相探讨,本人亲测好使,最后附上全部的js代码和css代码把
1 // Node object 2 3 function Node(id, pid, name, url, title, target, icon, iconOpen, open) { 4 5 this.id = id; 6 7 this.pid = pid; 8 9 this.name = name; 10 11 this.url = url; 12 13 this.title = title; 14 15 this.target = target; 16 17 this.icon = icon; 18 19 this.iconOpen = iconOpen; 20 21 this._io = open || false; 22 23 this._is = false; 24 25 this._ls = false; 26 27 this._hc = false; 28 29 this._ai = 0; 30 31 this._p; 32 33 }; 34 35 36 37 // Tree object 38 39 function dTree(objName) { 40 41 this.config = { 42 43 target : null, 44 45 folderLinks : true, 46 47 useSelection : true, 48 49 useCookies : true, 50 51 useLines : true, 52 53 useIcons : false,//我给改了,不想让显示图标,太丑了 0.0 想要的话,改成true 54 55 useStatusText : false, 56 57 closeSameLevel : false, 58 59 inOrder : false, 60 61 useCheckbox : true //新加的 62 63 } 64 65 this.icon = { 66 67 root : '/dtree/img/base.gif', 68 69 folder : '/dtree/img/folder.gif', 70 71 folderOpen : '/dtree/img/folderopen.gif', 72 73 node : '/dtree/img/page.gif', 74 75 empty : '/dtree/img/empty.gif', 76 77 line : '/dtree/img/line.gif', 78 79 join : '/dtree/img/join.gif', 80 81 joinBottom : '/dtree/img/joinbottom.gif', 82 83 plus : '/dtree/img/plus.gif', 84 85 plusBottom : '/dtree/img/plusbottom.gif', 86 87 minus : '/dtree/img/minus.gif', 88 89 minusBottom : '/dtree/img/minusbottom.gif', 90 91 nlPlus : '/dtree/img/nolines_plus.gif', 92 93 nlMinus : '/dtree/img/nolines_minus.gif' 94 95 }; 96 97 this.obj = objName; 98 99 this.aNodes = []; 100 101 this.aIndent = []; 102 103 this.root = new Node(-1); 104 105 this.selectedNode = null; 106 107 this.selectedFound = false; 108 109 this.completed = false; 110 111 }; 112 113 114 115 // Adds a new node to the node array 116 117 dTree.prototype.add = function(id, pid, name, url, title, target, icon, iconOpen, open) { 118 119 this.aNodes[this.aNodes.length] = new Node(id, pid, name, url, title, target, icon, iconOpen, open); 120 121 }; 122 123 124 125 // Open/close all nodes 126 127 dTree.prototype.openAll = function() { 128 129 this.oAll(true); 130 131 }; 132 133 dTree.prototype.closeAll = function() { 134 135 this.oAll(false); 136 137 }; 138 139 140 141 // Outputs the tree to the page 142 143 dTree.prototype.toString = function() { 144 145 var str = '<div class="dtree">\n'; 146 147 if (document.getElementById) { 148 149 if (this.config.useCookies) this.selectedNode = this.getSelected(); 150 151 str += this.addNode(this.root); 152 153 } else str += 'Browser not supported.'; 154 155 str += '</div>'; 156 157 if (!this.selectedFound) this.selectedNode = null; 158 159 this.completed = true; 160 161 return str; 162 163 }; 164 165 166 167 // Creates the tree structure 168 169 dTree.prototype.addNode = function(pNode) { 170 171 var str = ''; 172 173 var n=0; 174 175 if (this.config.inOrder) n = pNode._ai; 176 177 for (n; n<this.aNodes.length; n++) { 178 179 if (this.aNodes[n].pid == pNode.id) { 180 181 var cn = this.aNodes[n]; 182 183 cn._p = pNode; 184 185 cn._ai = n; 186 187 this.setCS(cn); 188 189 if (!cn.target && this.config.target) cn.target = this.config.target; 190 191 if (cn._hc && !cn._io && this.config.useCookies) cn._io = this.isOpen(cn.id); 192 193 if (!this.config.folderLinks && cn._hc) cn.url = null; 194 195 if (this.config.useSelection && cn.id == this.selectedNode && !this.selectedFound) { 196 197 cn._is = true; 198 199 this.selectedNode = n; 200 201 this.selectedFound = true; 202 203 } 204 205 str += this.node(cn, n); 206 207 if (cn._ls) break; 208 209 } 210 211 } 212 213 return str; 214 215 }; 216 217 218 219 // Creates the node icon, url and text 220 221 dTree.prototype.node = function(node, nodeId) { 222 223 var str = '<div class="dTreeNode">' + this.indent(node, nodeId); 224 225 if (this.config.useIcons) { 226 227 if (!node.icon) node.icon = (this.root.id == node.pid) ? this.icon.root : ((node._hc) ? this.icon.folder : this.icon.node); 228 229 if (!node.iconOpen) node.iconOpen = (node._hc) ? this.icon.folderOpen : this.icon.node; 230 231 if (this.root.id == node.pid) { 232 233 node.icon = this.icon.root; 234 235 node.iconOpen = this.icon.root; 236 237 } 238 239 str += '<img id="i' + this.obj + nodeId + '" src="' + ((node._io) ? node.iconOpen : node.icon) + '" alt="" />'; 240 241 } 242 243 244 245 if(this.config.useCheckbox == true && node.id != 0){ 246 str += '<label class="demo--label">' 247 + '<input type="checkbox" class="demo--radio" id="' + node.pid+ '_' + node.id 248 + '" onclick="javascript:' + this.obj + '.cc(' + node.id 249 + ',' + node.pid + ')"/>' 250 + '<span class="demo--checkbox demo--radioInput"></span>' 251 + '</label>'; 252 } 253 // if(this.config.useCheckbox == true && node.id != 0){ 254 // str += '<input type="checkbox" id="' + node.pid+ '_' + node.id 255 // + '" onclick="javascript:' + this.obj + '.cc(' + node.id 256 // + ',' + node.pid + ')"/>'; 257 // } 258 259 if (node.url) { 260 261 str += '<a id="s' + this.obj + nodeId + '" class="' + ((this.config.useSelection) ? ((node._is ? 'nodeSel' : 'node')) : 'node') + '" href="' + node.url + '"'; 262 263 if (node.title) str += ' title="' + node.title + '"'; 264 265 if (node.target) str += ' target="' + node.target + '"'; 266 267 if (this.config.useStatusText) str += ' onmouseover="window.status=\'' + node.name + '\';return true;" onmouseout="window.status=\'\';return true;" '; 268 269 if (this.config.useSelection && ((node._hc && this.config.folderLinks) || !node._hc)) 270 271 str += ' onclick="javascript: ' + this.obj + '.s(' + nodeId + ');"'; 272 273 str += '>'; 274 275 } 276 277 else if ((!this.config.folderLinks || !node.url) && node._hc && node.pid != this.root.id) 278 279 str += '<a href="javascript: ' + this.obj + '.o(' + nodeId + ');" class="node">'; 280 281 str += node.name; 282 283 if (node.url || ((!this.config.folderLinks || !node.url) && node._hc)) str += '</a>'; 284 285 str += '</div>'; 286 287 if (node._hc) { 288 289 str += '<div id="d' + this.obj + nodeId + '" class="clip" style="display:' + ((this.root.id == node.pid || node._io) ? 'block' : 'none') + ';">'; 290 291 str += this.addNode(node); 292 293 str += '</div>'; 294 295 } 296 297 this.aIndent.pop(); 298 299 return str; 300 301 }; 302 303 //复选框onclick事件 304 dTree.prototype.cc=function(nodeId, nodePid){ 305 //说明:checkbox的id由 nodePid + _ + nodeId 三部分组成 306 //获取当前节点的选中状态 307 var boo = $("#"+nodePid+"_"+nodeId).attr("checked"); 308 //1. 判断有无子节点,如果有,则全部选中,并且递归判断子节点是否还有子节点 309 childsSelected(nodeId, boo); 310 311 //2. 获取所有同级节点,判断是否都选中,如果都选中,则父节点也要选中 312 parentsSelected(nodePid); 313 } 314 315 //递归选中父节点,参数1:父节点,参数2:选中状态 316 function parentsSelected(pid) { 317 //1. 获取所有同级checkbox的id集合 318 var siblings = getChilds(pid); 319 //由于至少还会有调用方法的那个节点本身,所以siblings里至少有一个值 320 var flag = $("#"+siblings[0]).attr("checked"); 321 //如果flag为false,则不用看其他同级节点了,父节点的checkbox必然为false,为true的话,则继续看同级节点里有没有false 322 //只要有一个false,父节点都为false 323 if (flag){ 324 for (var i = 1; i < siblings.length; i++){ 325 if ($("#"+siblings[i]).attr("checked") != flag){ 326 flag = false; 327 break; 328 } 329 } 330 } 331 // 获取父节点的选中状态 (父节点的id,_的后面部分是子节点_的前面部分) 332 var originalCheck = $("input[id$='_"+siblings[0].split("_")[0]+"']").attr("checked"); 333 //如果父节点原本的选中状态和应该的选中状态不一致,则改变父节点选中状态,并递归调用本方法 334 if (originalCheck != flag){ 335 $("input[id$='_"+siblings[0].split("_")[0]+"']").attr("checked", flag); 336 var parentCheckBoxId = $("input[id$='_"+siblings[0].split("_")[0]+"']").attr("id"); 337 if (parentCheckBoxId != null){ 338 parentsSelected(parentCheckBoxId.split("_")[0]); 339 } 340 } 341 342 } 343 344 //递归选中子节点,参数1:父节点id, 参数2:选中状态 345 function childsSelected(pid, boo) { 346 //获取所有下一级节点的checkbox的id 347 var childs = getChilds(pid); 348 if (childs.length == 0){ 349 return; 350 } 351 //让所有子节点选中,并递归判断每一个子节点是否还有子节点,让每一层每一个都选中 352 for (var i = 0; i < childs.length; i++){ 353 $("#"+childs[i]).attr("checked",boo); 354 childsSelected(childs[i].split("_")[1], boo); 355 } 356 } 357 358 //获取下一级子节点的id 359 function getChilds(pid){ 360 var arr = new Array(); 361 $("input[id^='"+pid+"_']").each(function (i,chkbox) { 362 arr.push(chkbox.id); 363 }) 364 return arr; 365 } 366 367 368 369 // Adds the empty and line icons 370 371 dTree.prototype.indent = function(node, nodeId) { 372 373 var str = ''; 374 375 if (this.root.id != node.pid) { 376 377 for (var n=0; n<this.aIndent.length; n++) 378 379 str += '<img src="' + ( (this.aIndent[n] == 1 && this.config.useLines) ? this.icon.line : this.icon.empty ) + '" alt="" />'; 380 381 (node._ls) ? this.aIndent.push(0) : this.aIndent.push(1); 382 383 if (node._hc) { 384 385 str += '<a href="javascript: ' + this.obj + '.o(' + nodeId + ');"><img id="j' + this.obj + nodeId + '" src="'; 386 387 if (!this.config.useLines) str += (node._io) ? this.icon.nlMinus : this.icon.nlPlus; 388 389 else str += ( (node._io) ? ((node._ls && this.config.useLines) ? this.icon.minusBottom : this.icon.minus) : ((node._ls && this.config.useLines) ? this.icon.plusBottom : this.icon.plus ) ); 390 391 str += '" alt="" /></a>'; 392 393 } else str += '<img src="' + ( (this.config.useLines) ? ((node._ls) ? this.icon.joinBottom : this.icon.join ) : this.icon.empty) + '" alt="" />'; 394 395 } 396 397 return str; 398 399 }; 400 401 402 403 // Checks if a node has any children and if it is the last sibling 404 405 dTree.prototype.setCS = function(node) { 406 407 var lastId; 408 409 for (var n=0; n<this.aNodes.length; n++) { 410 411 if (this.aNodes[n].pid == node.id) node._hc = true; 412 413 if (this.aNodes[n].pid == node.pid) lastId = this.aNodes[n].id; 414 415 } 416 417 if (lastId==node.id) node._ls = true; 418 419 }; 420 421 422 423 // Returns the selected node 424 425 dTree.prototype.getSelected = function() { 426 427 var sn = this.getCookie('cs' + this.obj); 428 429 return (sn) ? sn : null; 430 431 }; 432 433 434 435 // Highlights the selected node 436 437 dTree.prototype.s = function(id) { 438 439 if (!this.config.useSelection) return; 440 441 var cn = this.aNodes[id]; 442 443 if (cn._hc && !this.config.folderLinks) return; 444 445 if (this.selectedNode != id) { 446 447 if (this.selectedNode || this.selectedNode==0) { 448 449 eOld = document.getElementById("s" + this.obj + this.selectedNode); 450 451 eOld.className = "node"; 452 453 } 454 455 eNew = document.getElementById("s" + this.obj + id); 456 457 eNew.className = "nodeSel"; 458 459 this.selectedNode = id; 460 461 if (this.config.useCookies) this.setCookie('cs' + this.obj, cn.id); 462 463 } 464 465 }; 466 467 468 469 // Toggle Open or close 470 471 dTree.prototype.o = function(id) { 472 473 var cn = this.aNodes[id]; 474 475 this.nodeStatus(!cn._io, id, cn._ls); 476 477 cn._io = !cn._io; 478 479 if (this.config.closeSameLevel) this.closeLevel(cn); 480 481 if (this.config.useCookies) this.updateCookie(); 482 483 }; 484 485 486 487 // Open or close all nodes 488 489 dTree.prototype.oAll = function(status) { 490 491 for (var n=0; n<this.aNodes.length; n++) { 492 493 if (this.aNodes[n]._hc && this.aNodes[n].pid != this.root.id) { 494 495 this.nodeStatus(status, n, this.aNodes[n]._ls) 496 497 this.aNodes[n]._io = status; 498 499 } 500 501 } 502 503 if (this.config.useCookies) this.updateCookie(); 504 505 }; 506 507 508 509 // Opens the tree to a specific node 510 511 dTree.prototype.openTo = function(nId, bSelect, bFirst) { 512 513 if (!bFirst) { 514 515 for (var n=0; n<this.aNodes.length; n++) { 516 517 if (this.aNodes[n].id == nId) { 518 519 nId=n; 520 521 break; 522 523 } 524 525 } 526 527 } 528 529 var cn=this.aNodes[nId]; 530 531 if (cn.pid==this.root.id || !cn._p) return; 532 533 cn._io = true; 534 535 cn._is = bSelect; 536 537 if (this.completed && cn._hc) this.nodeStatus(true, cn._ai, cn._ls); 538 539 if (this.completed && bSelect) this.s(cn._ai); 540 541 else if (bSelect) this._sn=cn._ai; 542 543 this.openTo(cn._p._ai, false, true); 544 545 }; 546 547 548 549 // Closes all nodes on the same level as certain node 550 551 dTree.prototype.closeLevel = function(node) { 552 553 for (var n=0; n<this.aNodes.length; n++) { 554 555 if (this.aNodes[n].pid == node.pid && this.aNodes[n].id != node.id && this.aNodes[n]._hc) { 556 557 this.nodeStatus(false, n, this.aNodes[n]._ls); 558 559 this.aNodes[n]._io = false; 560 561 this.closeAllChildren(this.aNodes[n]); 562 563 } 564 565 } 566 567 } 568 569 570 571 // Closes all children of a node 572 573 dTree.prototype.closeAllChildren = function(node) { 574 575 for (var n=0; n<this.aNodes.length; n++) { 576 577 if (this.aNodes[n].pid == node.id && this.aNodes[n]._hc) { 578 579 if (this.aNodes[n]._io) this.nodeStatus(false, n, this.aNodes[n]._ls); 580 581 this.aNodes[n]._io = false; 582 583 this.closeAllChildren(this.aNodes[n]); 584 585 } 586 587 } 588 589 } 590 591 592 593 // Change the status of a node(open or closed) 594 595 dTree.prototype.nodeStatus = function(status, id, bottom) { 596 597 eDiv = document.getElementById('d' + this.obj + id); 598 599 eJoin = document.getElementById('j' + this.obj + id); 600 601 if (this.config.useIcons) { 602 603 eIcon = document.getElementById('i' + this.obj + id); 604 605 eIcon.src = (status) ? this.aNodes[id].iconOpen : this.aNodes[id].icon; 606 607 } 608 609 eJoin.src = (this.config.useLines)? 610 611 ((status)?((bottom)?this.icon.minusBottom:this.icon.minus):((bottom)?this.icon.plusBottom:this.icon.plus)): 612 613 ((status)?this.icon.nlMinus:this.icon.nlPlus); 614 615 eDiv.style.display = (status) ? 'block': 'none'; 616 617 }; 618 619 620 621 622 623 // [Cookie] Clears a cookie 624 625 dTree.prototype.clearCookie = function() { 626 627 var now = new Date(); 628 629 var yesterday = new Date(now.getTime() - 1000 * 60 * 60 * 24); 630 631 this.setCookie('co'+this.obj, 'cookieValue', yesterday); 632 633 this.setCookie('cs'+this.obj, 'cookieValue', yesterday); 634 635 }; 636 637 638 639 // [Cookie] Sets value in a cookie 640 641 dTree.prototype.setCookie = function(cookieName, cookieValue, expires, path, domain, secure) { 642 643 document.cookie = 644 645 escape(cookieName) + '=' + escape(cookieValue) 646 647 + (expires ? '; expires=' + expires.toGMTString() : '') 648 649 + (path ? '; path=' + path : '') 650 651 + (domain ? '; domain=' + domain : '') 652 653 + (secure ? '; secure' : ''); 654 655 }; 656 657 658 659 // [Cookie] Gets a value from a cookie 660 661 dTree.prototype.getCookie = function(cookieName) { 662 663 var cookieValue = ''; 664 665 var posName = document.cookie.indexOf(escape(cookieName) + '='); 666 667 if (posName != -1) { 668 669 var posValue = posName + (escape(cookieName) + '=').length; 670 671 var endPos = document.cookie.indexOf(';', posValue); 672 673 if (endPos != -1) cookieValue = unescape(document.cookie.substring(posValue, endPos)); 674 675 else cookieValue = unescape(document.cookie.substring(posValue)); 676 677 } 678 679 return (cookieValue); 680 681 }; 682 683 684 685 // [Cookie] Returns ids of open nodes as a string 686 687 dTree.prototype.updateCookie = function() { 688 689 var str = ''; 690 691 for (var n=0; n<this.aNodes.length; n++) { 692 693 if (this.aNodes[n]._io && this.aNodes[n].pid != this.root.id) { 694 695 if (str) str += '.'; 696 697 str += this.aNodes[n].id; 698 699 } 700 701 } 702 703 this.setCookie('co' + this.obj, str); 704 705 }; 706 707 708 709 // [Cookie] Checks if a node id is in a cookie 710 711 dTree.prototype.isOpen = function(id) { 712 713 var aOpen = this.getCookie('co' + this.obj).split('.'); 714 715 for (var n=0; n<aOpen.length; n++) 716 717 if (aOpen[n] == id) return true; 718 719 return false; 720 721 }; 722 723 724 725 // If Push and pop is not implemented by the browser 726 727 if (!Array.prototype.push) { 728 729 Array.prototype.push = function array_push() { 730 731 for(var i=0;i<arguments.length;i++) 732 733 this[this.length]=arguments[i]; 734 735 return this.length; 736 737 } 738 739 }; 740 741 if (!Array.prototype.pop) { 742 743 Array.prototype.pop = function array_pop() { 744 745 lastElement = this[this.length-1]; 746 747 this.length = Math.max(this.length-1,0); 748 749 return lastElement; 750 751 } 752 753 };
View Code
1 .dtree { 2 font-family: Verdana, Geneva, Arial, Helvetica, sans-serif; 3 font-size: 11px; 4 color: #666; 5 white-space: nowrap; 6 } 7 .dtree img { 8 border: 0px; 9 vertical-align: middle; 10 } 11 .dtree a { 12 color: #333; 13 text-decoration: none; 14 } 15 .dtree a.node, .dtree a.nodeSel { 16 white-space: nowrap; 17 padding: 1px 2px 1px 2px; 18 } 19 .dtree a.node:hover, .dtree a.nodeSel:hover { 20 color: #333; 21 text-decoration: underline; 22 } 23 .dtree a.nodeSel { 24 background-color: #c0d2ec; 25 } 26 .dtree .clip { 27 overflow: hidden; 28 } 29 30 .demo--label{display:inline-block} 31 .demo--radio{display:none} 32 .demo--radioInput{background-color:#fff;border:1px solid rgba(0,0,0,0.15);border-radius:100%;display:inline-block;height:13px;margin-right:5px;margin-top:-1px;vertical-align:middle;width:13px;line-height:1} 33 .demo--radio:checked + .demo--radioInput:after{background-color:#57ad68;border-radius:100%;content:"";display:inline-block;height:9px;margin:2px;width:9px} 34 .demo--checkbox.demo--radioInput,.demo--radio:checked + .demo--checkbox.demo--radioInput:after{border-radius:0}
View Code