使用jQuery UI的.position(),我能够成功地将图像移动到图像列表的末尾…然而,我不知道如何让其他图像"向上移动"来填充空间。
我知道移动的图像是相对定位的,我相信这是导致其他图像"停留"在他们的位置的原因。问题是我不知道怎么把其他的移上来。(没有移动每一个图像,每次周围的另一个图像被移动,我无法看到它如何可能当我可以有任何未知数量的图像加载)
理想情况下,我想移动整个DIV上的DOM,与动画,但我不知道如何做到这一点,所以我不得不退回到使用。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>
这样的东西会为您工作吗?
我没有改变你的任何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
});
}
希望我的评论是有意义的,但这里是不太基本的概要:
- 现在,你的图像是绝对定位,他们都在左上角。为了使它们整齐地显示在垂直列中,我们需要给它们一个
top
量。但是多少钱呢?每张图片大约有150像素高,如果我们在底部加一个5像素的缓冲区,那就是155。第一个图像很简单;它需要在top:0
(或155 * 0)。第二张图像应该在top:155px
或(155 * 1)。第三张应该在top:310px
(或155 * 2)。看到图案了吗? (注意:我后来给每个数字加了40像素,以便给顶部的按钮留出空间。) - 所以我使用
.each()
来循环所有图像,并使用jQuery.attr()
方法,我给每个图像name="x"
,其中x从0开始,每个图像增加1。然后用.css()
,我给每个图像top:x * 155
,再次,其中x是该图像的name
。 - 所以现在我想让第一个图像(
name="0"
)到第三个图像的位置,第二个图像到第一个图像的位置,第三个图像到第二个图像的位置。我所要做的就是将第一个图像的名称设置为2(因此top
变成155 * 2),将第二个图像的名称设置为0,将第三个图像的名称设置为1。实际上,我所做的就是将每个图像的名称(除了第一张)减少1。这就是我在moveImages
函数中所做的。 - 对于第一张图像,我实际上也将其名称减少了1,因此它变成了-1。然后我选择
name
为-1的图像,并将其名称设置为图像总数减去1,即2。这意味着,无论你有多少张图片,这段代码都可以工作。
我希望这对你有帮助!如果它不能完全解决您的问题,我很乐意编辑我的代码。