【问题标题】:Rearrange the order HTML elements appear in with JavaScript or jQuery使用 JavaScript 或 jQuery 重新排列 HTML 元素出现的顺序
【发布时间】:2016-12-03 06:59:47
【问题描述】:

我正在构建一个模块化构建程序,并且有一个侧面板,用户可以在其中添加模块的代码以使其出现在列表中。

列表只是包含文本的 span 标签。由于它们在 HTML 中已经按照设定的顺序排列,因此当它们可见时,它们会按默认顺序显示,而不是每次出现新的时都出现在列表底部一个是可见的。

我的解决方法是让所有跨度都定位为绝对,并使用一些 jQuery/JS 进行一些计算并将最新的可见跨度移动到底部。

此代码用于将输入字段和按钮移动到列表底部:

var searchModule = 0;
$("#add_module_button").click(function(){
   searchModule = "#" + document.getElementById("add_module_input").value;
   $(searchModule).css('display', 'block');
   visibleModules = $('.side_module:visible').length * 50 + "px";
   $('#add_a_module').css('top', visibleModules);
});

有没有更好的解决方案来重新排列 HTML 元素,而无需使用绝对定位来伪装它?

【问题讨论】:

标签: javascript jquery html


【解决方案1】:

如果我猜对了,这实际上很容易。使用 jQuery.append()。如果您使用 jQuery.append() 将一个项目附加到它已经包含在其中的同一个容器中,则该项目实际上是从其当前位置删除并附加到最​​后。据我阅读您的问题,这就是您想要的。下面的例子展示了基本思想......

$('#container').append($('#three').css('display', 'block'));
$('#container').append($('#one').css('display', 'block'));
$('#container').append($('#five').css('display', 'block'));
.item{
  display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
  <div class="item" id="one">One</div>
  <div class="item" id="two">Two</div>
  <div class="item" id="three">Three</div>
  <div class="item" id="four">Four</div>
  <div class="item" id="five">Five</div>
</div>

【讨论】:

  • 谢谢,我以前没有遇到过追加,总的来说对 JS 来说还是很新的。不过,这有很大帮助,谢谢!
猜你喜欢
  • 2017-04-16
  • 1970-01-01
  • 2011-05-08
  • 1970-01-01
  • 2016-08-31
  • 2016-10-30
  • 2012-12-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多