简体   繁体   中英

How to set multiple Jquery-UI resizable?

I use Jquery-UI to resize different div but they have different "type" with different parameters (minWidth, minHeight, aspectratio ...). This code works but maybe the final code will have 20 "type".

How could I optimize this code ?

$(".child").resizable({
    containment: "parent",
    resize: function( event,ui ){
        if(ui.element.attr('data-type')=="type-b"){
            // specific code to type-b
        }
        if($(this).attr('data-type')=="type-c"){
            // specific code to type-c
        }
    },
    stop: function (event,ui) {
        $.ajax({
            url: "save.php",
            type: "POST",
            data: {id: ui.element.attr('id')},
            success: function (child_id) {
                var parent_id = $('#main').attr('id'),
                    full_id =(parent_id+"_"+child_id),
                    child_width = ui.size.width,
                    child_height = ui.size.height,
                    t=JSON.parse(sessionStorage.getItem(full_id));

                t.width=child_width;t.height=child_height;
                sessionStorage.setItem(full_id,JSON.stringify(t));
            }
        });
        if(ui.element.attr('data-type')=="type-a"){
            // specific code to type-a
        }
        if($(this).attr('data-type')=="type-b"){
            // specific code to type-b
        }
    }
});

$(".child.type-a").resizable({
    minWidth: 200,
    minHeight: 50,
    handles : "e,w"
}),$(".child.type-b").resizable({
    minWidth: 160,
    minHeight: 110,
    handles : "e,w"
}),$(".child.type-c").resizable({
    minWidth: 300,
    minHeight: 185,
    aspectRatio: 1.618/1
});

If each is unique, then you won't get too far away from what you have. One option would be to store all the variables in an object and iterate each to set the options. Example: https://jsfiddle.net/hovqphko/

$(function() {
  var resOptions = {
    "type-a": {
      minWidth: 200,
      minHeight: 50,
      handles: "e,w"
    },
    "type-b": {
      minWidth: 160,
      minHeight: 110,
      handles: "e,w"
    },
    "type-c": {
      minWidth: 300,
      minHeight: 185,
      aspectRatio: 1.618 / 1
    }
  };

  $(".child").resizable({
    containment: "parent"
  });

  $.each(resOptions, function(k, v) {
    console.log("Setting", k, "to", v);
    $("." + k).resizable("option", v);
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM