簡體   English   中英

動態更改放置元素的高度和寬度

[英]change height and width of dropped element dynamically

我創建了一個拖放文件,當單擊放置的元素時,用戶將在其中輸入像 3*4 這樣的坐標,使用標量因子獲得元素的高度和寬度。 我想更改放置元素的高度和寬度。 任何人都可以幫忙嗎?

 $(document).ready(function () {

  var x = null;

  // Make element draggable
  $(".drag").draggable({
    helper: 'clone',
    cursor: 'move',
    tolerance: 'fit'
  });

  var i = 1, j = 0;
  var x1, x2, y1, y2, tmp, tmp2;
  var sf = pf; 

  $("#droppable").droppable({

    drop: function(e, ui) {

      var attr = ui.helper.attr('id');  
      if (typeof attr == typeof undefined || attr == false) {
        ui.helper.attr('id',"id"+i);
      }  
      tmp = ui.helper.attr('id');
      x = ui.helper.clone().bind("click",'img',function(){

        alert("clicked"+ ui.helper.attr('id') + tmp);
        leftpos = ui.offset.left-210;
        toppos = ui.offset.top;
        var cor = window.prompt("Enter coordinates x1,y1");
        var c = cor.split(',');
        var w = c[0]*sf;
        var h = c[1]*sf;
        w = w/2;
        h = h/2;
        ui.helper.width(leftpos-w);
        ui.helper.height(toppos-h);
      });

      x.draggable({
        helper: 'original',
        containment: '#droppable',
        tolerance: 'fit',
      }); 

      x.appendTo('#droppable');
      ui.helper.remove();
      i++;
    }
  });
});

您的代碼中缺少一些東西。

  • click事件處理程序是一個closure ,這意味着即使事件處理程序函數在其定義的范圍之外執行,它也可以訪問ui.helper 但是要改變寬度和高度,你需要通過this關鍵字來引用當前的事件有界對象。
  • 變量pf未定義,所以我定義了一個同名的局部變量。
  • 根據您當前的邏輯,目標放置的項目看起來很奇怪,因此我在 jsfiddle 下方將寬度和高度的靜態值設置為 300。

JS代碼:

x= ui.helper.clone().bind("click", 'img', function() {
    //leftpos = ui.helper.offset.left - 210;
    //toppos = ui.helper.offset.top;
    leftpos = ($(this).offset().left) - 210;
    toppos = ($(this).offset().top);
    ...

    //ui.helper.width(leftpos-w);
    //ui.helper.height(toppos-h);
    $(this).width(300);
    $(this).height(300);

現場演示@JSFiddle

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM