如何在图像列表中移动元素?与JQuery

how can i move an element within a list of images? with JQuery

本文关键字:元素 JQuery 移动 图像 列表      更新时间:2023-09-26

我有一个图像列表

<img src="image-1.jpg" />
<img src="image-2.jpg" />
<img src="image-3.jpg" />
<img src="image-4.jpg" />
<img src="image-5.jpg" />

将它们重新排序,使image-1位于底部的最佳方法是什么?(但不一定是image-1)

编辑:最好不使用JQuery UI之类的东西。
我希望这是完成尽可能少的代码。

简单易行

$(function(){
    var parent=$("img").parent();
    $("img:first").appendTo(parent);
});

如果您不想创建一个动态可排序列表,而只是在寻找一种重新排序图像的方法。您可以尝试以下操作:

$("img[src$='image-1.jpg']").insertAfter("img[src$='image-5.jpg']");

这将允许您查找图像并根据图像的src移动它们。

http://api.jquery.com/category/manipulation/

查看DOMinsertion中可用的不同方法

您可以通过使用jQuery UI来实现这一点:

http://jqueryui.com/demos/sortable/

(假设你想让它是动态的,如果不是,你应该进一步解释确切的情况)

你想要这样的东西吗?它将1、2、3、4、5排序为5、4、3、2、1

<div id="reorder">
    <img src="http://www.google.com.tr/images/srpr/logo3w.png" />
    <img src="http://l.yimg.com/a/i/ww/met/logo/20100909/yahoo_logo_tr.png" />
    <img src="http://www.rev2.org/wp-content/uploads/2009/06/bing-logo.png" />
    <img src="http://a.l.yimg.com/a/i/us/sch/yhs4/altavista_logo.png" />
    <img src="http://searchcdn.infospace.com/Dogpile-8.0.1.353/Content/Img/img_trans.gif?av=1353" />
</div>
<script>
    $(function() {
        $('#reorder').click(function() {
            $("#reorder").randomize("img");
        });
    });
    (function($) {
        var onerandom = Math.random();
        $.fn.randomize = function(childElem) {
            return this.each(function() {
                var $this = $(this);
                var elems = $this.children(childElem);
                elems.sort(function() { return (Math.round(onerandom)-0.5); });  
                $this.remove(childElem);  
                for(var i=0; i < elems.length; i++)
                $this.append(elems[i]);      
            });    
        }
    })(jQuery);
</script>