【发布时间】:2021-07-28 06:08:50
【问题描述】:
我有一个 div,其中包含代表列表成员的子 div 列表。我正在尝试创建一组按钮来在列表中向上或向下移动列表项。我可以检索列表的索引,但我不知道如何更改当前元素的位置
function moveUp(){
let list = document.getElementById("answer").children;
let targeted = document.getElementById("answer").getElementsByClassName("active")
var temp = Array.prototype.indexOf.call(list,targeted[0])
console.log(temp)
if(temp > 0){
list[temp] = list[temp-1];
list[temp-1] = targeted[0]
}
}
function moveDown(){
let list = document.getElementById("answer").children;
var temp = Array.prototype.indexOf.call(list,document.getElementById("answer").getElementsByClassName("active"))
if(temp < list.length-1){
list.swap(temp, temp+1);
}
}
<div class="white" id="answer" name="answer" style="height:21.125vh; width:35vw; box-sizing: border-box; overflow: auto;">
<div id="1" class="" style="height: 5vh; font-size: 2vw; color: black; text-align: center; justify-content: center; overflow: auto;">test</div>
<div id="2" class="active" style="height: 5vh; font-size: 2vw; color: black; text-align: center; justify-content: center; overflow: auto;">commands</div>
<div id="21" class="" style="height: 5vh; font-size: 2vw; color: black; text-align: center; justify-content: center; overflow: auto;">Final</div>
</div>
这是我要移动的 div 的测试列表。我尝试的测试是选择带有 innerhtml“命令”的 div 并将其向上移动,但没有任何反应。按向下按钮会出错
Uncaught TypeError: list.swap is not a function
如果我能在这方面得到一些帮助,那就太好了。
【问题讨论】:
-
你用什么浏览器?
标签: javascript html css arrays