jquery在dom中更改元素位置

时间:2016-10-14 23:36:30

标签: jquery html

嘿,我想改变DOM中某个元素的位置,例如.offach中的.off-date,但是如果这些元素在页面上是两次或更多,则它预备两个或多个元素而不是一个,所以结果就是我得到了页面上的四个.off-date元素而不是两个..我可以以某种方式阻止这种情况吗?任何建议都欢迎..

if ($(window).width() < 767) {

        $(".teach2 .off-place").prependTo($(".teach2 .off-date"));

     }


       <div class="teacher-box teach2">

            <span class="typo off-name">Magdalene</span>
            <span class="typo off-type">with partners</span>
            <span class="typo off-date">wed DEC 15 </span>
            <span class="typo off-time">19.30 - 20.30</span> 
            <span class="typo off-place">at home</span>

        </div>

        <div class="teacher-box teach2">

            <span class="typo off-name">Magdalene</span>
            <span class="typo off-type">with partners</span>
            <span class="typo off-date">wed DEC 15 </span>
            <span class="typo off-time">19.30 - 20.30</span>
            <span class="typo off-place">at home</span> 

        </div>

3 个答案:

答案 0 :(得分:1)

以下是您在纯CSS中可以实现的目标。

&#13;
&#13;
.teacher-box {
  display: flex;
}
.typo {
  margin: 0 1px;
}
.off-name {
  order: 1;
}
.off-type {
  order: 2;
}
.off-date {
  order: 3;
}
.off-time {
  order: 4;
}
.off-place {
  order: 5;
}
@media (max-width: 768px) {
  .off-name {
    order: 1;
  }
  .off-type {
    order: 2;
  }
  .off-date {
    order: 4;
  }
  .off-time {
    order: 5;
  }
  .off-place {
    order: 3;
  }
}
&#13;
<div class="teacher-box teach2">

  <div class="typo off-name">Magdalene</div>
  <div class="typo off-type">with partners</div>
  <div class="typo off-date">wed DEC 15 </div>
  <div class="typo off-time">19.30 - 20.30</div>
  <div class="typo off-place">at home</div>
  
</div>
&#13;
&#13;
&#13;

假设您正试图在768px处更改窗口大小调整的内容位置。

您可以将teachebox设置为flex布局并编写媒体查询以更改为768px;

答案 1 :(得分:0)

您必须指定要更改的元素。 XPath或CSS选择器可以帮助解决这个问题。

在旁注中,您似乎正在尝试创建自适应网页。也许你应该研究另一种方法?灵活的布局,响应式设计 - 它已经被发明出来。

答案 2 :(得分:0)

您需要使用.each()来迭代每个.off-place,因此您可以将其添加到同一DIV中的.off-date

&#13;
&#13;
$("#but").click(function() {
  $(".teach2 .off-place").each(function() {
    $(this).prependTo($(this).siblings(".off-date"));
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="but">Click to move</button>
<div class="teacher-box teach2">

  <span class="typo off-name">Magdalene</span>
  <span class="typo off-type">with partners</span>
  <span class="typo off-date">wed DEC 15 </span>
  <span class="typo off-time">19.30 - 20.30</span> 
  <span class="typo off-place">at home</span>

</div>

<div class="teacher-box teach2">

  <span class="typo off-name">Magdalene</span>
  <span class="typo off-type">with partners</span>
  <span class="typo off-date">wed DEC 15 </span>
  <span class="typo off-time">19.30 - 20.30</span>
  <span class="typo off-place">at home</span> 

</div>
&#13;
&#13;
&#13;