? Сортировка элементов по количеству символов
Вам необходимо использовать JavaScript для сортировки элементов по их длине / размеру.
Это базовый пример использования Array.prototype.sort()
для сортировки по количеству символов каждого из них (Node.innerText
):
// Sort the elements according to their number of characters:
const categoryList = document.getElementById('categoryList');
Array.from(categoryList.children).sort((a, b) => {
const charactersA = a.innerText.length;
const charactersB = b.innerText.length;
if (charactersA < charactersB) {
return -1;
} else if (charactersA === charactersB) {
return 0;
} else {
return 1;
}
}).forEach((element) => {
// When appending an element that is already a child, it will not
// be duplicated, but removed from the old position first and then
// added to the new one, which is exactly what we want:
categoryList.appendChild(element);
});
#categoryList {
font-family: monospace;
display: flex;
flex-direction: row;
flex-wrap: wrap;
align-content: flex-start;
list-style: none;
padding: 0;
margin: 0;
width: 220px;
border-right: 2px solid #000;
}
#categoryList > li {
background: #000;
color: #FFF;
padding: 4px 8px;
margin: 0 4px 4px 0;
border-radius: 2px;
}
<ul id="categoryList">
<li>Literature</li>
<li>Science Fiction and Fantasy</li>
<li>Harry Potter</li>
<li>Movies and Films</li>
<li>Books</li>
</ul>
? Сортировка элементов по фактической ширине
innerText
может работать нормально для моноширинных шрифтов, но для других вы можете использоватьHTMLElement.offsetWidth
вместо того, чтобы учитывать фактическую ширину элемента:
/**
* Get the actual width of an element, taking into account margins
* as well:
*/
function getElementWidth(element) {
const style = window.getComputedStyle(element);
// Assuming margins are in px:
return element.offsetWidth + parseInt(style.marginLeft) + parseInt(style.marginRight);
}
// Sort the elements according to their actual width:
const categoryList = document.getElementById('categoryList');
Array.from(categoryList.children).sort((a, b) => {
const aWidth = getElementWidth(a);
const bWidth = getElementWidth(b);
if (aWidth < bWidth) {
return -1;
} else if (aWidth === bWidth) {
return 0;
} else {
return 1;
}
}).forEach((element) => {
// When appending an element that is already a child, it will not
// be duplicated, but removed from the old position first and then
// added to the new one, which is exactly what we want:
categoryList.appendChild(element);
});
#categoryList {
font-family: monospace;
display: flex;
flex-direction: row;
flex-wrap: wrap;
align-content: flex-start;
list-style: none;
padding: 0;
margin: 0;
width: 220px;
border-right: 2px solid #000;
}
#categoryList > li {
background: #000;
color: #FFF;
padding: 4px 8px;
margin: 0 4px 4px 0;
border-radius: 2px;
}
<ul id="categoryList">
<li>Literature</li>
<li>Science Fiction and Fantasy</li>
<li>Harry Potter</li>
<li>Movies and Films</li>
<li>Books</li>
</ul>
? Элементы сортировки, минимизирующие пустое пространство
Вы также можете реализовать собственный алгоритм сортировки, чтобы сортировать их другим способом.Например, вы можете захотеть минимизировать пустое пространство в каждой строке:
/**
* Get the actual width of an element, taking into account margins
* as well:
*/
function getElementWidth(element) {
const style = window.getComputedStyle(element);
// Assuming margins are in px:
return element.offsetWidth + parseInt(style.marginLeft) + parseInt(style.marginRight);
}
/**
* Find the index of the widest element that fits in the available
* space:
*/
function getBestFit(elements, availableSpace) {
let minAvailableSpace = availableSpace;
let bestFitIndex = -1;
elements.forEach((element, i) => {
if (element.used) {
return;
}
const elementAvailableSpace = availableSpace - element.width;
if (elementAvailableSpace >= 0 && elementAvailableSpace < minAvailableSpace) {
minAvailableSpace = elementAvailableSpace;
bestFitIndex = i;
}
});
return bestFitIndex;
}
/**
* Get the first element that hasn't been used yet.
*/
function getFirstNotUsed(elements) {
for (let element of elements) {
if (!element.used) {
return element;
}
}
}
// Sort the elements according to their actual width:
const categoryList = document.getElementById('categoryList');
const totalSpace = categoryList.clientWidth;
const items = Array.from(categoryList.children).map((element) => {
return {
element,
used: false,
width: getElementWidth(element),
};
});
const totalItems = items.length;
// We want to keep the first element in the first position:
const firstItem = items[0];
const sortedElements = [firstItem.element];
firstItem.used = true;
// We calculate the remaining space in the first row:
let availableSpace = totalSpace - firstItem.width;
// We sort the other elements:
for (let i = 1; i < totalItems; ++i) {
const bestFitIndex = getBestFit(items, availableSpace);
let item;
if (bestFitIndex === -1) {
// If there's no best fit, we just take the first element
// that hasn't been used yet to keep their order as close
// as posible to the initial one:
item = getFirstNotUsed(items);
availableSpace = totalSpace - item.width;
} else {
item = items[bestFitIndex];
availableSpace -= item.width;
}
sortedElements.push(item.element);
item.used = true;
}
sortedElements.forEach((element) => {
// When appending an element that is already a child, it will not
// be duplicated, but removed from the old position first and then
// added to the new one, which is exactly what we want:
categoryList.appendChild(element);
});
#categoryList {
font-family: monospace;
display: flex;
flex-direction: row;
flex-wrap: wrap;
align-content: flex-start;
list-style: none;
padding: 0;
margin: 0;
width: 220px;
border-right: 2px solid #000;
}
#categoryList > li {
background: #000;
color: #FFF;
padding: 4px 8px;
margin: 0 4px 4px 0;
border-radius: 2px;
}
<ul id="categoryList">
<li>Literature</li>
<li>Science Fiction and Fantasy</li>
<li>Harry Potter</li>
<li>Movies and Films</li>
<li>Books</li>
</ul>
✨ Чтобы он выглядел еще лучше
Наконец, вы можете применить flex: 1 0 auto
к каждому ребенку в списке после того, как выотсортировать их, чтобы удалить любое нерегулярное пустое пространство между ними:
/**
* Get the actual width of an element, taking into account margins
* as well:
*/
function getElementWidth(element) {
const style = window.getComputedStyle(element);
// Assuming margins are in px:
return element.offsetWidth + parseInt(style.marginLeft) + parseInt(style.marginRight);
}
/**
* Find the index of the widest element that fits in the available
* space:
*/
function getBestFit(elements, availableSpace) {
let minAvailableSpace = availableSpace;
let bestFitIndex = -1;
elements.forEach((element, i) => {
if (element.used) {
return;
}
const elementAvailableSpace = availableSpace - element.width;
if (elementAvailableSpace >= 0 && elementAvailableSpace < minAvailableSpace) {
minAvailableSpace = elementAvailableSpace;
bestFitIndex = i;
}
});
return bestFitIndex;
}
/**
* Get the first element that hasn't been used yet.
*/
function getFirstNotUsed(elements) {
for (let element of elements) {
if (!element.used) {
return element;
}
}
}
// Sort the elements according to their actual width:
const categoryList = document.getElementById('categoryList');
const totalSpace = categoryList.clientWidth;
const items = Array.from(categoryList.children).map((element) => {
return {
element,
used: false,
width: getElementWidth(element),
};
});
const totalItems = items.length;
// We want to keep the first element in the first position:
const firstItem = items[0];
const sortedElements = [firstItem.element];
firstItem.used = true;
// We calculate the remaining space in the first row:
let availableSpace = totalSpace - firstItem.width;
// We sort the other elements:
for (let i = 1; i < totalItems; ++i) {
const bestFitIndex = getBestFit(items, availableSpace);
let item;
if (bestFitIndex === -1) {
// If there's no best fit, we just take the first element
// that hasn't been used yet to keep their order as close
// as posible to the initial one:
item = getFirstNotUsed(items);
availableSpace = totalSpace - item.width;
} else {
item = items[bestFitIndex];
availableSpace -= item.width;
}
sortedElements.push(item.element);
item.used = true;
}
sortedElements.forEach((element) => {
// When appending an element that is already a child, it will not
// be duplicated, but removed from the old position first and then
// added to the new one, which is exactly what we want:
categoryList.appendChild(element);
});
// If you want to add a class to make the elements inside the list
// expand, you have to do it after sorting them. Otherwise, they would
// already take all available horizontal space and the sorting algorithm
// won't do anything:
categoryList.classList.add('expand');
#categoryList {
font-family: monospace;
display: flex;
flex-direction: row;
flex-wrap: wrap;
align-content: flex-start;
list-style: none;
padding: 0;
margin: 0;
width: 220px;
border-right: 2px solid #000;
}
#categoryList > li {
background: #000;
color: #FFF;
padding: 4px 8px;
margin: 0 4px 4px 0;
border-radius: 2px;
}
#categoryList.expand > li {
flex: 1 1 auto;
}
<ul id="categoryList">
<li>Literature</li>
<li>Science Fiction and Fantasy</li>
<li>Harry Potter</li>
<li>Movies and Films</li>
<li>Books</li>
</ul>