Javascript.RU

Создать новую тему Ответ
 
Опции темы Искать в теме
  #1 (permalink)  
Старый 11.05.2020, 09:40
Новичок на форуме
Отправить личное сообщение для alexander909090 Посмотреть профиль Найти все сообщения от alexander909090
 
Регистрация: 09.05.2020
Сообщений: 2

построить Dom дерево каталогов и файлов
помогите сделать дерево (как на рисунке-можно без изображений папок) из этого массива:



const data = [
  {
    'folder': true,
    'title': 'Pictures',
    'children': [
      {
        'title': 'logo.png'
      },
      {
        'folder': true,
        'title': 'Vacations',
        'children': [
          {
            'title': 'spain.jpeg'
          }
        ]
      }
    ]
  },
  {
    'folder': true,
    'title': 'Desktop',
    'children': [
      {
        'folder': true,
        'title': 'screenshots',
        'children': null
      }
    ]
  },
  {
    'folder': true,
    'title': 'Downloads',
    'children': [
      {
        'folder': true,
        'title': 'JS',
        'children': null
      },
      {
        'title': 'nvm-setup.exe'
      },
      {
        'title': 'node.exe'
      }
    ]
  },
  {
    'title': 'credentials.txt'
  }
];


пробовал делать по этому примеру: https://plnkr.co/edit/zuCWg1ONoC4QB8D4?p=preview, но поскольку объекты data разные не получается, возможно причина в пустых названиях ключей...вроде пример и норм, но не получается.
Ответить с цитированием
  #2 (permalink)  
Старый 11.05.2020, 12:23
Аватар для рони
Профессор
Отправить личное сообщение для рони Посмотреть профиль Найти все сообщения от рони
 
Регистрация: 27.05.2010
Сообщений: 33,068

дерево файловой системы
alexander909090,

<!doctype html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
<style type="text/css">
.folder:before {
    width: 45px;
    height: 45px;
    display: block;
    background-image:url(http://icons.iconarchive.com/icons/wilnichols/alumin-folders/128/Generic-Purple-Folder-icon.png);
    content:'';
    background-size: cover;
}
.folder {
     display: flex;
}

.file:before {
    width: 45px;
    height: 45px;
    display: block;
    background-image:url(http://icons.iconarchive.com/icons/icons8/windows-8/128/Very-Basic-File-icon.png);
    content:'';
    background-size: cover;
}
ul{
    list-style: none;
    padding-top: 8px;
}
body > ul > li  {
    border-top: 3px solid #0000FF;

}
ul > li{
    margin-left: -20px;
    margin-top: 20px;
}

</style>


</head>
<body>
  <script>
const data = [
  {
    'folder': true,
    'title': 'Pictures',
    'children': [
      {
        'title': 'logo.png'
      },
      {
        'folder': true,
        'title': 'Vacations',
        'children': [
          {
            'title': 'spain.jpeg'
          }
        ]
      }
    ]
  },
  {
    'folder': true,
    'title': 'Desktop',
    'children': [
      {
        'folder': true,
        'title': 'screenshots',
        'children': null
      }
    ]
  },
  {
    'folder': true,
    'title': 'Downloads',
    'children': [
      {
        'folder': true,
        'title': 'JS',
        'children': null
      },
      {
        'title': 'nvm-setup.exe'
      },
      {
        'title': 'node.exe'
      }
    ]
  },
  {
    'title': 'credentials.txt'
  }
];
const createTree = ar => {
let html = `<ul>`;
for(let {folder, title, children} of ar) {
    children = (Array.isArray(children)) ? createTree(children) : '';
    folder = folder ? 'folder' : 'file';
    html += `<li class="${folder}">${title}${children}</li>`;
}
html+=`</ul>`;
return html
}
document.body.insertAdjacentHTML('beforeend', createTree(data))
</script>
</body>
</html>
Ответить с цитированием
  #3 (permalink)  
Старый 11.05.2020, 15:26
Аватар для Malleys
Профессор
Отправить личное сообщение для Malleys Посмотреть профиль Найти все сообщения от Malleys
 
Регистрация: 20.12.2009
Сообщений: 1,714

Без зависимостей...
<body><style>
body {
  font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", sans-serif;
}

ul.app {
	margin: 0;
	padding: 20px;
}
ul.app ul {
	padding: 0 0 0 30px;
}
ul.app li {
	list-style: none;
	font-size: 1em;
	color: #000;
	padding: 10px 5px;
	margin: 0 -5px;
	white-space: nowrap;
	overflow: hidden;
	display: block;
	width: 100%;
	text-overflow: ellipsis;
}
ul.app li::before {
	display: inline-block;
	vertical-align: middle;
	margin-right: 10px;
	width: 24px;
	text-align: center;
	line-height: 12px;
}
ul.app li.file::before {
	content: url("data:image/svg+xml;utf8,\
	  <svg width='15' height='19' fill='none' xmlns='http://www.w3.org/2000/svg'>\
		<path d='\
			M10 8C8.34 8 7 6.66 7 5V1H3c-1.1 0-2 .9-2 2v13c0 1.1.9 2 2 2\
			h9c1.1 0 2-.9 2-2V8h-4zM8 5c0 1.1.9 2 2 2h3.59L8 1.41V5zM3 0\
			h5l7 7v9c0 1.66-1.34 3-3 3H3c-1.66 0-3-1.34-3-3V3c0-1.66 1.34\
			-3 3-3z' fill='black'/>\
	  </svg>");
}
ul.app li.folder::before {
	content: url("data:image/svg+xml;utf8,\
	  <svg width='20' height='16' fill='none' xmlns='http://www.w3.org/2000/svg'>\
		<path d='\
			M18.784 3.87a1.565 1.565 0 0 0-.565-.356V2.426c0-.648-.523-1.171-1.15\
			-1.171H8.996L7.908.25A.89.89 0 0 0 7.302 0H2.094C1.445 0 .944.523.944\
			1.171v2.3c-.21.085-.398.21-.565.356a1.348 1.348 0 0 0-.377 1.004l.398 9.83\
			C.42 15.393 1.048 16 1.8 16h15.583c.753 0 1.36-.586 1.4-1.339l.398-9.83\
			c.021-.313-.125-.69-.397-.962zM1.843 3.41V1.191c0-.146.104-.272.25-.272\
			H7.26l1.234 1.088c.083.042.167.104.293.104h8.282c.125 0 .25.126.25.272V3.41\
			H1.844zm15.54 11.712H1.78a.47.47 0 0 1-.481-.46l-.397-9.83c0-.147.041\
			-.252.125-.356a.504.504 0 0 1 .377-.147H17.78c.125 0 .272.063.377\
			.147.083.083.125.209.125.334l-.418 9.83c-.021.272-.23.482-.481.482z\
		' fill='black'/>\
	  </svg>");
}
</style>
<script>
const data = [
	{
		folder: true,
		title: "Pictures",
		children: [
			{ title: "logo.png" },
			{
				folder: true,
				title: "Vacations",
				children: [
					{ title: "spain.jpeg" }
				]
			}
		]
	},
	{
		folder: true,
		title: "Desktop",
		children: [
			{
				folder: true,
				title: "screenshots",
				children: null
			}
		]
	},
	{
		folder: true,
		title: "Downloads",
		children: [
			{
				folder: true,
				title: "JS",
				children: null
			},
			{ title: "nvm-setup.exe" },
			{ title: "node.exe" }
		]
	},
	{ title: "credentials.txt" }
];

function renderTree(entries) {
	const list = document.createElement("ul");
	for(const entry of entries) {
		const item = document.createElement("li");
		item.textContent = entry.title;
		item.classList.add(entry.folder ? "folder" : "file");
		list.appendChild(item);
		if(entry.folder && entry.children != null)
			list.appendChild(renderTree(entry.children));
	}
	return list;
}

const app = renderTree(data);
app.classList.add("app");
document.body.appendChild(app);
</script>

Последний раз редактировалось Malleys, 11.05.2020 в 15:29.
Ответить с цитированием
Ответ



Опции темы Искать в теме
Искать в теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Как избежать ошибки по ограничению открытых файлов? Tipylja Node.JS 3 17.08.2018 19:43
Dom дерево клик по элементу без id Денис01952 Элементы интерфейса 10 14.06.2017 22:08
инициализация плагинов до вставки html-я в DOM FanAizu jQuery 3 19.01.2014 01:16
Возврат всех файлов изи дерева каталогов kilogram Серверные языки и технологии 2 13.06.2012 19:22
Построить дерево по xml. mmfStudent jQuery 8 01.09.2010 04:21