Javascript-форум (https://javascript.ru/forum/)
-   jQuery (https://javascript.ru/forum/jquery/)
-   -   sorting position block (https://javascript.ru/forum/jquery/26352-sorting-position-block.html)

join 05.03.2012 19:55

sorting position block
 
Привет усем.
Написал функцию сортировки позиций блоков.
В операх ниже 10.10 - работает не совсем корректно.
Как решить этот проблем?
Может уже есть готовые решения? кто встречал - поделитеs

сам код:
Код:

<!doctype html>
<head>
<style>
#test{
background-color: #eee;
border:2px solid #aaa;
position:relative;
height:50px;
display:block;
}
.bob{
border:black solid 1px;
height:50px;
width:50px;
z-index:0;
background-color:orange;
position:absolute;
}
</style>
<script src="js/jquery-1.7.1.min.js"></script>
<script>
$(function(){
  $("div#test>div").addClass('pazB');
       
  var speed=300;
  var $test=$('#test');
  var nom=[1,2,3,4,5,6,7,8];
    for(var w=0; w<nom.length; w++){
    $test.append('<div class="bob">'+nom[w]+'</div>');
    };
    var x=0;
  function addL(){
  $('.bob').each(function(elem){
    x+=50;
    return $(this).css({left:x+'px'});
  });
  };
  addL();
 
 /*sorting*/
 function so(){
  var arr=$('.bob').get();
  var war=arr.sort(sort1);
    $(war).appendTo('#test');
 }

  function sort1(){
  return Math.random()>0.5 ?1:Math.random()<=0.5?-1:0;
  }
 
function sorting(){
  so();
 
  var arrs=$('.bob').get();
  arrs.sort(sort3);
  function sort3(alfa, beta){
    var aa=$(alfa,'.bob');
    var bb=$(beta,'.bob');
 
    var app=$(aa).position();
    var bpp=$(bb).position();
 
    var su=Math.random();
    if(su>=-1){
      var fpp=$('.bob').eq(0).position();
      var ll=$('.bob:last');
      $(ll).animate(fpp,600);
 
      return $(aa).animate(bpp,600);
      $(bb).animate(app,600);   
    }
    else{ return false; }
 };
};


  $('.sort').click(function(){ sorting() });
});
</script>
</head>
<body>

<div id="test"></div>
<button class="sort">sort</button>
</body>
</html>


рони 06.03.2012 01:04

визуализация сортировки
 
Цитата:

Сообщение от join
return $(aa).animate(bpp,600);
$(bb).animate(app,600);

Странный return.
Сортировать позицию можно проще ... вариант ниже
<!DOCTYPE html>
<html>
<head>
<style>
body{
  background-color: #B0C4DE;
}

#test{
  margin:0 auto;
  background-color:#eee;
  position:relative;
  height:54px;
  display:block;
  width:508px;
  padding:6px 4px;
}

.bob{
  line-height:50px;
  text-align:center;
  margin:0;
  border:black solid 1px;
  height:50px;
  width:50px;
  z-index:0;
  background-color:orange;
  position:absolute;
}

.red{
  background-color:#FF0000;
  z-index:100;
}

.color{
  color:#FFFFFF;
  font-size:28px;
  -webkit-animation:color 5s ease-in-out infinite;
  -moz-animation:color 5s ease-in-out infinite;
  -o-animation:color 5s ease-in-out infinite;
  animation:color 5s ease-in-out infinite;
}

@keyframes color{
  0%{
    background-color:#FF0000;
  }

  17%{
    background-color:#FFA500;
  }

  34%{
    background-color:#FFFF00;
  }

  51%{
    background-color:#008000;
  }

  68%{
    background-color:#0000FF;
  }

  85%{
    background-color:#000080;
  }

  100%{
    background-color:#800080;
  }
}

@-webkit-keyframes color{
  0%{
    background-color:#FF0000;
  }

  17%{
    background-color:#FFA500;
  }

  34%{
    background-color:#FFFF00;
  }

  51%{
    background-color:#008000;
  }

  68%{
    background-color:#0000FF;
  }

  85%{
    background-color:#000080;
  }

  100%{
    background-color:#800080;
  }
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(function() {
    Array.prototype.shuffle = function(min, max) {
        min = min || 0;
        max = ++max || this.length;
        var len = max - min;
        max = len - this.length;
        this.length = len;
        for (var a = this.length - 1; 0 <= a; a--) {
            if (a < max) break;
            var b = Math.floor(Math.random() * a),
                c = void 0 === this[b] ? b + min : this[b];
            this[b] = void 0 === this[a] ? a + min : this[a];
            this[a] = c
        }
        this.reverse();
        this.length -= max;
        return this
    };
    var arr = Array(10).shuffle(0, 20).sort(function(a, b) {
        return a - b
    });


    var speed = 500;
    var $test = $("#test");
    var nom = [];
    $.each(arr, function(x, num) {
       nom[x]=x;
       $test.append($("<div/>",{"class" : "bob",text : num,css : {
            left: 6 + x*50 + "px"
        }}));
    });


    nom.shuffle();
    $(".bob").each(function(i, elem) {
        var x = 6 + 50 * nom[i];
        $(this).animate({
            left: x + "px"
        }, speed * i)
    });
    var i = 0,
        j = 0,
        count = nom.length - 1;

    function sorting() {
        if (i < count)
            if (j < count - i) {
                $(".bob").removeClass("red");
                $(".bob").eq(j).addClass("red");
                $(".bob").eq(j + 1).addClass("red");
                if (nom[j] > nom[j + 1]) {
                    var max = nom[j];
                    nom[j] = nom[j + 1];
                    nom[j + 1] = max;
                    $(".bob").each(function(k,
                        elem) {
                        var x = 6 + 50 * nom[k];
                        $(this).delay(300).animate({
                            left: x + "px"
                        }, speed * Math.abs(nom[j]-nom[j + 1]) ,function() {
                            if (!$(".bob").queue("fx").length) {
                                $(".bob").removeClass("red");
                                sorting()
                            }
                        })
                    })
                } else {
                    j++;
                    sorting()
                }
            } else j = 0, i++;
        else $(".bob").addClass("color")
    }
    $(".sort").click(function() {
        sorting()
    })
});
</script>
</head>
<body>

<div id="test"></div>
<button class="sort">sort</button>
</body>
</html>

join 06.03.2012 12:42

To: рони

Интересный вариант, если есть массив с числами.
Но мне не подходит.Так как блоки не имеют чисел.
В своём примере я вставил массив чисел для наглядности.
Но все равно спасибо.

Есть плагин Isotope, http://github.com/desandro/isotope.
Сортирует, фильтрует.
Пытаюсь вытащить из него метод shuffle(понять как работает).
Но пока не могу,плагин написан в стиле ооп.

рони 06.03.2012 14:27

Цитата:

Сообщение от join
блоки не имеют чисел.

смотрите добавленный вариант выше. перемешивает элементы ориентируясь только на класс,но принцип тотже, плюс защита от повторного нажатия во время анимации.

join 06.03.2012 17:05

рони - вы отличный программист )

ссылку на мозайку кину позже, в личку.

Борис К 19.01.2022 12:27

Цитата:

Сообщение от join
рони - вы отличный программист )

Без сомнений!


Часовой пояс GMT +3, время: 06:46.