我在一条水平线上有以下 DOM 元素:
- 包含一行文本的 div;即“ Hello World ”。此 div 的宽度与包含文本的宽度相同。
- 用于交换两个 div 的按钮。
- 包含列表框的 div。此 div 的宽度与包含的列表框相同。
使用 float
或 position:absolute
我可以在一行上正确对齐这些元素。但是,当用户单击交换按钮时,div 应该交换位置。我不希望从 DOM 中删除 div 并将它们重新添加到彼此的位置。这是因为这些元素实际上是 Javascript 对象(更具体地说是 Google Closure Library 组件),它们包含变量并附加了事件处理程序。是否可以使用 CSS 交换 div,而不为 div 分配静态宽度?
简化示例:
<div style="position:relative; height:60px;">
<div style="float:left;">Our Team</div>
<div style="float:left;"><button onclick="swap();">swap home/away</button></div>
<div style="float:left;"><select><option>Opponent A</option><option>Opponent B</option></select></div>
</div>
<div style="clear:both;"></div>
当用户单击按钮时,第一个(我们的团队)和第三个(对手的)div 应该在浏览器中视觉交换,最好不要从 DOM 中删除元素。
最佳答案
I would prefer not to remove the divs from the DOM and adding them again in each other's place. That's because the elements are actually Javascript objects (Google Closure Library components to be more specific) that hold variables and have event handlers attached to them.
最好的解决方案是移动 DOM 中的元素。这样做将保留现有的事件处理程序,这意味着您的代码应该仍然有效:
http://jsfiddle.net/thirtydot/LGGW2/
function swap() {
var target1 = document.querySelector('#swapMe > :first-child');
var target2 = document.querySelector('#swapMe > :last-child');
var parent = target1.parentNode;
parent.insertBefore(target1, null);
parent.insertBefore(target2, parent.firstChild);
}
我假设您已经有了对要交换的元素的引用,因此您可以用任何合适的内容替换 document.querySelector
行。
写完这个答案后,我搜索了一个更通用的“交换”函数并找到了这个,看起来不错:Swap 2 html elements and preserve event listeners on them
关于javascript - 交换两个水平对齐的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13564045/