gpt4 book ai didi

javascript - 如何使用 JS 对 HTML 元素数组进行排序

转载 作者:行者123 更新时间:2023-12-05 04:32:36 25 4
gpt4 key购买 nike

我想对一组 HTML 元素进行排序。我想按 css 左属性值对它们进行排序。这意味着左值最小的元素是我要排序的数组的第一个元素,左值最大的元素是我要排序的数组的最后一个元素。

如果有人给我答案,请不要用jquery给我答案,因为我对jquery一无所知。

const games = document.querySelectorAll('.games');

games.sort((a, b) => {
return parseInt(window.getComputedStyle(a).getPropertyValue('left')) - parseInt(window.getComputedStyle(b).getPropertyValue('left'))
})
.games {
position: absolute;
transform: scale(1);
transition: left 0.4s ease;
width: 20vw;
height: 20vw;
border-radius: 2.5vw;
background-color: white;
display: flex;
justify-content: center;
}

.games:nth-of-type(1) {
left: 6.5vw;
}

.games:nth-of-type(2) {
left: 40;
}

.games:nth-of-type(3) {
left: calc(100vw - 6.5vw - 20vw);
/* same position if you write: right: 6.5vw*/
}
<div class="games"></div>
<div class="games"></div>
<div class="games"></div>

最佳答案

你缺少括号,你需要一个展开来使它成为一个可排序的数组。

现代浏览器(早期的 EDGE 除外)可以在 querySelectorAll nodeList 上执行 forEach,但是要映射、过滤和排序,您需要转换为数组。

这是一个更简洁的版本。注意我使用 parseFloat 来摆脱单位

const games = [...document.querySelectorAll('.games')]; // has to be an array to sort it
const getProp = (elem,prop) => window.getComputedStyle(elem).getPropertyValue(prop);
console.log(games)
games.sort((a, b) => parseFloat(getProp(a,'left')) - parseFloat(getProp(b,'left')));

// debug

games.forEach(game => game.textContent += ': ' + getProp(game,'left'))

console.log(games)
.games {
position: absolute;
transform: scale(1);
transition: left 0.4s ease;
width: 20vw;
height: 20vw;
border-radius: 2.5vw;
background-color: white;
display: flex;
justify-content: center;
}

.games:nth-of-type(1) {
left: 6.5vw;
}

.games:nth-of-type(2) {
left: 40;
}

.games:nth-of-type(3) {
left: calc(100vw - 6.5vw - 20vw);
/* same position if you write: right: 6.5vw*/
}
<div class="games">1</div>
<div class="games">2</div>
<div class="games">3</div>

关于javascript - 如何使用 JS 对 HTML 元素数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71626269/

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