gpt4 book ai didi

javascript - 根据宽度/大小对多个 Flexbox 行中的元素进行排序

转载 作者:行者123 更新时间:2023-11-29 23:21:31 25 4
gpt4 key购买 nike

假设我有一组这样的列表项(某种类别):

ul.categoryList {
display: flex;
flex-direction: row;
flex-wrap: wrap;
width: 180px;
}

ul.categoryList > li {
list-style: none;
}
<ul class="categoryList">
<li>Literature</li>
<li>Science Fiction and Fantasy</li>
<li>Harry Potter</li>
<li>Movies and Films</li>
<li>Books</li>
</ul>

还有这个<ul><div>里面用max-width如果调整窗口大小或在不同的分辨率/设备(手机、平板电脑等)上,这可能会发生变化。

如您所见,一些列表项比其他列表项长。假设这个 <ul> 的容器只能包含列表项 Science Fiction and Fantasy还有一点,所以下一项将转到下一行,因为它不适合放在同一行。

正如您可能看到的那样,问题在于 LiteratureBooks可以一起在同一行,但由于它们不是连续的,它们最终会在不同的行,这同样适用于其他元素。

因此,我没有将一些最短的元素放在一起以减少行数,而是得到 5 行(实际上每个元素一行),这很耗费空间。

有什么办法可以解决这个问题吗?可以仅使用 CSS 完成还是我需要 JavaScript?

最佳答案

👉按字符数对元素排序

您需要使用 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>

关于javascript - 根据宽度/大小对多个 Flexbox 行中的元素进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50439298/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com