简体   繁体   中英

jQuery UI .draggable()

good day!

Just have a question if any of you came across my issue. Issue is that I want to make the dynamically created div elements to be draggable. Yes, can achieve it by $('.frameHolder').draggable() . But the problem is when the divs are up to a thousand it causes the browser to get really slow (like 800ms - measured by performance.now()).

Here's the snippet:

var frames = [];

for (var i = 1; i <= 100; i++) {
  frames.push('<div id="frame' + i + '" class="frame"><div id="frameHolder' + i + '" class="frameHolder"></div></div>');
}

$('.frameHolder').draggable({
  containment: $('#layerFrameContainer .layerFrame),
  axis: 'x',
  cursor: 'pointer',
  helper: 'clone',
  grid: [10, 10]
});

Thanks guys!

Another way to make a large number of elements draggable, without a larger load time upfront, is to do it on demand. Instead of making all of the elements draggable just make those that need to be draggable as they are needed. From my comments, I tested a number of methods to decrease the load time and got down to ~500 ms.

Consider the following: https://jsfiddle.net/Twisty/mpns7w3n/11/

HTML

<div id="layerFrameContainer">
  <div class="layerFrame">
  </div>
</div>

JavaScript

$(function() {
  var frames = [];

  function dragInit(t) {
    if (t.hasClass("ui-draggable")) {
      return;
    }
    console.log("Making frame[" + t.parent().index() + "] > frameHolder draggable");
    t.draggable({
      containment: $('#layerFrameContainer .layerFrame'),
      axis: 'x',
      cursor: 'pointer',
      helper: 'clone',
      grid: [10, 10]
    });
  }

  var t0 = performance.now();
  for (var i = 1; i <= 1000; i++) {
    var frame = $("<div>", {
      id: "frame-" + i
    });
    var frameHolder = $("<div>", {
      id: "frameHolder-" + i,
      class: "frameHolder"
    }).appendTo(frame);
    frames.push(frame);
    $(".layerFrame").append(frame);
  }
  var t1 = performance.now();
  console.log("Call to loop took " + (t1 - t0) + " milliseconds.");
  $(".layerFrame").on("mouseover", ".frameHolder", function(e) {
    dragInit($(this));
  });
  var t2 = performance.now();
  console.log("Call to assign draggable took " + (t2 - t1) + " milliseconds.");
});

The initial load time will be under 200 ms.

As the user moves the mouse across the page, the user must mouseover before they can click an element. We can use this to trigger .draggable() for that target. It is then draggable when the user clicks on the element.

Even if the user does not click, the element is now draggable. As the user cannot click an element before he mouses over it, no element will ever be un-draggable. Faster loading and same user experience.

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