使用.position()重新定位图像或DIV,并使元素折叠以填充空间

时间:2016-10-30 02:46:53

标签: jquery jquery-ui jquery-animate

使用.position()用于jQuery UI,我能够成功地将图像移动到图像列表的末尾...但是我不知道如何让其他图像“向上移动”填补空间。

我知道移动的图像是相对定位的,我相信这是导致其他图像“停留”在他们的位置的原因。问题是我不确定如何移动其他的。 (没有移动每个图像,每次移动它周围的另一个图像,我无法看到当我可以加载任何未知数量的图像时它是如何可能的)

理想情况下,我想用动画在DOM上移动整个DIV,但我无法弄清楚如何做到这一点,所以我不得不回到使用.position()

JS Fiddle Link

$('#btn').click(function() {
  $('#elemA').position({
    my: 'left top',
    at: 'left bottom',
    of: $('#elemC'),
    collision: 'none',
    using: function(pos) {
      $(this).animate(pos, "fast")
    }
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div>

  <button id="btn">click</button>


  <div id="elemA">
    <img src="https://cdn.pbrd.co/images/l1wpxNXG9.jpg">
  </div>

  <div id="elemB">
    <img src="https://cdn.pbrd.co/images/l1xYdbrhS.jpg">
  </div>

  <div id="elemC">
    <img src="https://cdn.pbrd.co/images/l1yt0skhN.jpg">
  </div>

</div>

1 个答案:

答案 0 :(得分:0)

this之类的内容会对您有用吗?

我没有更改任何HTML,我在CSS中所做的就是制作图片position:absolute,所以这里是jQuery:

$(document).ready(function() {
  $('img').each(function(i) {
    $(this).attr('name', i).css({
      top: 40 + ($(this).attr('name') * 155) + 'px'
    })
  }); // Set the initial image positions
  $('#btn').click(moveImages); // Add click handler to button
});

function moveImages() {
  $('img').each(function() { // Loop over all your images
    var imgNum = $(this).attr('name'); // Grab the numerical name
    $(this).attr('name', imgNum - 1); // Whatever that number is, subtract 1
    $('img[name=-1]').attr('name', $('img').length - 1); // Change the -1 to be the highest number
    $(this).animate({
      top: 40 + ($(this).attr('name') * 155) + 'px'
    }); // Multiply the new number by 155, and animate to that position
  });
}

希望我的评论是有道理的,但这里是不那么基本的纲要:

  1. 现在你的图像绝对定位,它们都在左上角。为了让它们整齐地显示在垂直列中,我们需要为它们提供top金额。但是多少钱?好吧,每个图像大约150像素高,如果我们在底部添加一个5像素的缓冲区,那就是155.第一张图像很简单;它需要在top:0(或155 * 0)。第二张图像应为top:155px或(155 * 1)。第三个应该是top:310px(或155 * 2)。看模式? (注意:我之后为这些数字添加了40个像素,以便为顶部的按钮腾出空间。)
  2. 所以我使用.each()遍历所有图像,并使用jQuery .attr()方法,我给每个图像name="x",其中x从0开始并向上移动1每张图片。然后使用.css()我再次给每张图片top:x * 155,其中x是该图片的name
  3. 所以现在我希望第一张图像(name="0")转到第三张图像的位置,第二张图像转到第一张图像的位置,第三张图像转到第二张图像的位置。我所要做的就是将第一个图像的名称设置为2(因此它top变为155 * 2),第二个图像的名称设置为0,第三个图像& #39; s的名称为1.我真正做的就是将每个图像的名称(第一个除外)减少1.这就是我在moveImages中所做的事情功能
  4. 对于第一张图片,我实际上也将其名称减1,因此它变为-1。然后我选择name为-1的图像,并将其名称设置为图像总数减1 ,即2。这意味着,无论如何,此代码都将有效你有很多照片。
  5. 我希望这有帮助!如果它没有完全解决您的问题,我很乐意编辑我的代码。