javascript 将 DIV 元素移动到父元素的底部(作为最后一个子元素)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3415480/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Moving a DIV element to bottom of parent (as last child)
提问by mwieczorek
I'm trying to create a continually rotating banner for the top of the homepage of a site I'm developing. The best way that I can figure to keep it constantly in rotation is to take the first DIV (firstChild) and move it to the end of the stack once it's slid out of view.
我正在尝试为我正在开发的网站的主页顶部创建一个不断旋转的横幅。我能想到的保持它不断旋转的最好方法是获取第一个 DIV (firstChild) 并在它滑出视图后将其移动到堆栈的末尾。
This:
这:
<div id='foo0'></div>
<div id='foo1'></div>
<div id='foo2'></div>
<div id='foo3'></div>
Should become this:
应该变成这样:
<div id='foo1'></div>
<div id='foo2'></div>
<div id='foo3'></div>
<div id='foo0'></div>
I use the Prototype framework... and I've tried to do this by cloning the element using my own method and inserting it into the bottom of the parent DIV, but I find that not all of the style attributes are being carried over, and I'd like to abandon this method because I don't want what's being moved to be a copy/clone of the element, but the actual element itself.
我使用 Prototype 框架...并且我尝试通过使用我自己的方法克隆元素并将其插入到父 DIV 的底部来做到这一点,但我发现并不是所有的样式属性都被继承了,我想放弃这种方法,因为我不希望被移动的内容是元素的副本/克隆,而是实际元素本身。
Thanks.
谢谢。
回答by Ryan Kinal
Here's some plain javascript to do it, assuming the div has a valid parent:
这里有一些简单的 javascript 来做到这一点,假设 div 有一个有效的父级:
var d = document.getElementById('foo0');
d.parentNode.appendChild(d);
Essentially you get the node, then append it to its parent. appendChild, if the node is already part of the DOM, will move the node from its current position to the new position in the DOM.
本质上,您获取节点,然后将其附加到其父节点。appendChild, 如果节点已经是 DOM 的一部分,则将节点从其当前位置移动到 DOM 中的新位置。
回答by tomerz
wrap your divs with a parent div:
用父 div 包裹你的 div:
var parentElement = document.querySelector("#yourParentDiv");
parentElement.appendChild(parentElement.firstElementChild);

