1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
| <!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8" />
<title>Arbre</title>
<style>
.cache{display:none;}
.pointer{cursor:pointer;}
.red{background:red;}
li{margin:15px;display:flex;align-items:center;justify-content:flex-start;}
#famille div{width:120px;}
</style>
</head>
<body>
<div id="famille"></div>
<script>
const tab={
"Marianne":{
"Michel":{
"Marc":{
"Momo":{
"Mauricette":null,
"Mathis":"Marthe"
},
"Maurice":{
"Michou":"Manon",
"Manuela":{
"Manolo":"Manu"
}
}
}
},
"Martine":"Morgane",
"Maya":null,
"Madeleine":{
"Mehdi":null,
"Maxime":{
"Maelis":null,
"Marius":{
"Marguerite":null,
"Marjorie":"Maud",
"Magalie":null
}
}
}
}
}
document.addEventListener("DOMContentLoaded",()=>{
let li0=document.createElement("li"),
div0=document.createElement("div"),
sp0=document.createElement("span"),
ul0=document.createElement("ul");
document.getElementById("famille").append(ul0);
// coloration des ascendants
const col=ind=>{
ind.addEventListener("mouseover",()=> {
for(i=3;i<ind.id.length+1;i++){
document.getElementById(ind.id.substring(0,i)).classList.add("red");
}
})
ind.addEventListener("mouseout",()=> {
for(i=3;i<ind.id.length+1;i++){
document.getElementById(ind.id.substring(0,i)).classList.remove("red");
}
})
};
// création de l'arbre dom
const run=(t,ref,pre)=>{
// pour les ancêtres
if(typeof t=="object"){
let num=0;
for(let i in t){num++;
let li=li0.cloneNode(),
div=div0.cloneNode(),
sp=sp0.cloneNode();
sp.textContent=i;
// masquage / affichage des descendants
sp.addEventListener("click",(e)=>{
if(e.target.parentElement.nextSibling){
e.target.parentElement.nextSibling.classList.toggle("cache");
if(sp.textContent.indexOf("+")!=-1){
sp.textContent=sp.textContent.replace("+","-")
}
else{
sp.textContent=sp.textContent.replace("-","+")
}
}
});
ref.append(li);
li.append(div);
sp.id="id"+pre+num;
div.append(sp);
col(sp)
// membres avec enfants
if(t[i]!=null){
let ul=ul0.cloneNode();
ul.classList.add("cache");
li.append(ul);
sp.textContent+=" +";
sp.classList.add("pointer");
run(t[i],ul,pre+num)
}
}
}
// membres sans enfant
else{
let li=li0.cloneNode(),
div=div0.cloneNode(),
sp=sp0.cloneNode();
sp.textContent=t;
sp.id="id"+pre+1;
ref.append(li);
li.append(div);
div.append(sp);
col(sp)
}
}
run(tab,document.querySelector("#famille ul"),"")
document.querySelectorAll("#famille ul")[0].classList.remove("cache");
})
</script>
</body>
</html> |
Partager