如何改变这些div的顺序?
我有一列 div。我试图做到这一点,以便当我单击给定的 div 时,该 div 会根据 div 的位置替换上面或下面的 div 的位置。如果你看看结果就更好理解了 - http://jsfiddle.net/SuperBoi45/vgVnj/
几乎可以工作了。请注意,当您单击底部的 div 时,它会向上移动。但是当我想再次单击该 div 时,它应该会向下移动。但它并没有这样做。您能指出我可以做些什么来完成这项工作吗?下面是快速查看的代码:
<div id="colors">
<div id="red"></div>
<div id="blue"></div>
<div id="yellow"></div>
<div id="green"></div>
</div>
JavaScript:
var colors = Array.prototype.slice.call(
$('colors').getElementsByTagName('div'));
colors.forEach(function(e, i) {
colors[i].onclick = function() {
var a = colors[i + 1],
b = colors[i - 1],
_this = this,
node;
node = !a ? b : a;
this.parentNode.insertBefore(node, _this);
};
});
function $(id) {
return document.getElementById(id);
}
如果我单击顶部的 div,它应该向下移动,而下面的 div 应该向上移动到原来的位置。如果我单击中间的两个 div 之一,它应该会上升,而原来位于其上方的 div 会下降。如果我点击底部的 div,它应该会上升。
I have a column of divs. I'm trying to make it so that when I click a given div, that div replaces the position of the div above or below depending on where the div is. It's better understood if you look at the result -- http://jsfiddle.net/SuperBoi45/vgVnj/
It almost works. Notice how when you click the div at the bottom, it goes up. But when I want to click that div again, it's supposed to go back down. But it doesn't do that. Can you please point out what I can do to make this work. Here is the code for a quick view:
<div id="colors">
<div id="red"></div>
<div id="blue"></div>
<div id="yellow"></div>
<div id="green"></div>
</div>
JavaScript:
var colors = Array.prototype.slice.call(
$('colors').getElementsByTagName('div'));
colors.forEach(function(e, i) {
colors[i].onclick = function() {
var a = colors[i + 1],
b = colors[i - 1],
_this = this,
node;
node = !a ? b : a;
this.parentNode.insertBefore(node, _this);
};
});
function $(id) {
return document.getElementById(id);
}
If I click the top div, it should go down and the one below it should go up where it used to be. If I click one of the two middle divs, it should go up and the one that used to be above it go down. If I click the bottom div, it should go up.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想你正在寻找这个。
工作演示
I think you are looking for this.
Working demo
问题在于您对颜色的编号..这里我更新了解决方案,以便以更好的方式处理数字..
http://jsfiddle.net/vgVnj/5/
仅供参考,不熟悉 MOO 工具,因此使用原生 JS 方法
the problem was with your numbering of the colours.. here i have updated the solution to work with the numbers in a better way..
http://jsfiddle.net/vgVnj/5/
FYI not familiar with MOO Tools so using native JS methods