2016-06-19 2 views
0

Я не уверен, как это сделать. Им с помощью JQuery перетаскивания, и мне нужно, чтобы захватить позиции сетки:jQuery Draggable, конвертировать позицию в процентах

$("#draggable .item").draggable({ 
     containment: "#dragablle", 
     snap: '.gridlines', 
     stop: function(event, ui) { 
      console.log(ui) 
     } 
    }); 

Глядя на приемнике объекта от остановки события:

Object { top=178, left=950} 

нужно преобразовать верхнее и левое значение в проценты, так что я могу примените элемент .item как встроенный стиль. Родительская «#draggable» ширина и высота будут динамическими, поэтому мне нужен процент, а не пиксель. Поэтому, когда экран изменяется, все останется прежним (положение) в пределах родительского элемента

+0

Пожалуйста, проверьте мой ответ и попробуйте, посмотрите, подходит ли он для ваших нужд. – kolunar

+0

Ваш вопрос и ожидаемый результат не являются достаточно подробными, пожалуйста, укажите ваш html-ресурс, если это возможно. –

ответ

4

Если вы используете jQueryUI Draggable

Попробуйте это:

$("#draggable .item").draggable({ 
    containment: "#draggable", 
    snap: '.gridlines', 
    stop: function() { 
     var l = (100 * parseFloat($(this).position().left/parseFloat($(this).parent().width()))) + "%" ; 
     var t = (100 * parseFloat($(this).position().top/parseFloat($(this).parent().height()))) + "%" ; 
     $(this).css("left", l); 
     $(this).css("top", t); 
    } 
}); 
+0

Спасибо, я попробовал решение для тура, но получаю ошибку «TypeError: $ (...). Position (...). Left не является функцией« – Alko

+0

@Alko. Я сделал обновление выше, попробуйте без скобок после слева и сверху. Это была ошибка. – Luka

+0

Спасибо, что сработало. – Alko

1

Для того, чтобы захватить позиции сетки, вы могли используйте опцию grid: [x,y]. Вам не нужно преобразовывать верхние и левые значения в проценты, если вы хотите иметь привязку к сетке, тем самым вам нужно вычислить позиции в соответствии с вашей динамической шириной и высотой по событию $(window).resize().

Попробуйте запустить фрагмент ниже в режиме Full Page,

var grid_x = 10; 
 
var grid_y = 10; 
 
var snapThreshold = 5; 
 
var snapWhileResizing = true; 
 
var old_w, old_h; 
 
$(function() { 
 
    old_w = $("#draggable").width(); 
 
    old_h = $("#draggable").height(); 
 
    $("#label-old-dimen").html(old_w + ' x ' + old_h); \t 
 
    $("#draggable .item").draggable({ 
 
     containment: "parent", 
 
     grid: [grid_x, grid_y], 
 
     stop: function(){ 
 
      var l = $(this).position().left; 
 
      var t = $(this).position().top; 
 
      var mod_l = l % grid_x; 
 
      var mod_t = t % grid_y; \t \t \t 
 
      l = (mod_l > snapThreshold) ? (l + (grid_x - mod_l)) : l - mod_l; 
 
      t = (mod_t > snapThreshold) ? (t + (grid_y - mod_t)) : t - mod_t; \t \t \t \t 
 
      $(this).html(l + ' x ' + t); 
 
      $(this).data("left", l); 
 
      $(this).data("top", t); 
 
      $(this).css("left", l); 
 
      $(this).css("top", t); \t \t \t 
 
     } 
 
    }); 
 

 
    $("#snapWhileResizing").change(function(){ 
 
     snapWhileResizing = $(this).is(':checked'); 
 
    }); 
 
}); 
 

 
$(window).resize(function() { 
 
    var new_w = window.innerWidth; 
 
    var new_h = window.innerHeight; 
 
    $("#label-new-dimen").html(new_w + ' x ' + new_h); 
 
    var mod_w = new_w % grid_x; 
 
    var mod_h = new_h % grid_y; 
 
    new_w = ((mod_w > snapThreshold) ? (new_w + (grid_x - mod_w)) : new_w - mod_w) - 40; 
 
    new_h = ((mod_h > snapThreshold) ? (new_h + (grid_y - mod_h)) : new_h - mod_h) - 50; 
 
    
 
    if(old_w != new_w) 
 
     old_w = $("#draggable").width(); 
 
    if(old_h != new_h) 
 
     old_h = $("#draggable").height(); 
 
    
 
    $("#draggable").width(new_w); 
 
    $("#draggable").height(new_h); 
 

 
    $("#label-old-dimen").html(new_w + ' x ' + new_h);  
 
    $("#draggable .item").each(function(){ 
 
     var old_l, l, new_l, mod_l; 
 
     var old_t, t, new_t, mod_t;    
 
     old_l = l = $(this).data("left"); 
 
     old_t = t = $(this).data("top"); 
 
     new_l = $(this).position().left; 
 
     new_t = $(this).position().top; 
 
     
 
     l = (new_w/old_w) * old_l; 
 
     t = (new_h/old_h) * old_t;    
 
     mod_l = l % grid_x; 
 
     mod_t = t % grid_y;    
 
     new_l = (mod_l > snapThreshold) ? (l + (grid_x - mod_l)) : l - mod_l; 
 
     new_t = (mod_t > snapThreshold) ? (t + (grid_y - mod_t)) : t - mod_t;    
 
     if(old_w != new_w){   
 
      $(this).data("left", l);    
 
      $(this).css("left", snapWhileResizing ? new_l : l);     
 
     } 
 
     if(old_h != new_h && $("#draggable").height() > 200){  
 
        $(this).data("top", t); 
 
      $(this).css("top", snapWhileResizing ? new_t : t); 
 
     }    
 

 
     $(this).html(parseInt(l) + ' x ' + parseInt(t) + '<br />' + parseInt(new_l) + ' x ' + parseInt(new_t));  
 
    });  
 
});
#draggable .item { 
 
    width: 100px; 
 
    height: 100px; 
 
    padding: 0.5em; 
 
    border: 1px solid #555; 
 
    background-color:#efefef; 
 
    position: absolute; 
 
    top: 0; 
 
    cursor: move; 
 
} 
 
#draggable { 
 
    position: relative; 
 
    min-width: 200px; 
 
    height: 100%; 
 
    min-height: 200px; 
 
    overflow: hidden; 
 
    background-image: url(https://dl.dropboxusercontent.com/u/1094060/bg-dots.png); 
 
    background-repeat: repeat; 
 
    background-position: left top; 
 
} 
 
#label-old-dimen, #label-new-dimen { 
 
    background-color: white; 
 
    border: 1px solid gray; 
 
} 
 
.no-select { 
 
    -webkit-user-select: none; 
 
    -moz-user-select: none;  
 
    -ms-user-select: none;  
 
    user-select: none; 
 
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"> 
 
<script src="//code.jquery.com/jquery-1.10.2.js"></script> 
 
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script> 
 
<span id="label-new-dimen"></span> 
 
<span id="label-old-dimen"></span> 
 
<input type="checkbox" id="snapWhileResizing" name="snapWhileResizing" checked /> 
 
<label for="snapWhileResizing" class="no-select">snapWhileResizing</label> 
 
<div id="draggable" class="ui-widget-content"> 
 
    <div class="item">Drag me around</div> 
 
    <div class="item">Drag me around</div> 
 
</div>

Установка snapWhileResizing = false отключит привязки к сетке при изменении размера окна.

Note: converting top and left values into percentage will not snap to any grid when resizing. Also, enabling snapWhileResizing will cause slight shifting in items positions when resizing the windows many times.

Смежные вопросы