开发者

How to Disallow `var drag` depending on `checkbox` checked?

开发者 https://www.devze.com 2023-01-07 03:56 出处:网络
Moo开发者_如何学运维tools: How to Allow and Disallow var drag depending on checkbox checked or not?

Moo开发者_如何学运维tools: How to Allow and Disallow var drag depending on checkbox checked or not?

window.addEvent('domready',function() {
  var z = 2;
  $$('#dragable').each(function(e) {
    var drag = new Drag.Move(e,{
      grid: false,
      preventDefault: true,
      onStart: function() {
        e.setStyle('z-index',z++);
      }
    });
  });
});
function check(tag){
  if(tag.checked){
    //checkbox checked
    //How to Disallow Drag.Move for #dragable ?
    //Unfortunately so it does not work - drag.destroy(); drag.removeEvents();
  }else{
    //How to Allow Drag.Move for #dragable ?
  }
}
<input type="checkbox" onClick="check(this);">
<div id="dragable">Drag-able DIV</div>


Store the instance of Drag in MooTools Element Store so when the checkbox is clicked, we can retrieve this instance and manipulate it.

Drag.Move is an extension to the base Drag class, and if you see the docs, you will notice it has two methods for this situation:

  • attach
  • detach

You need to call these methods on the drag object that gets created when you call new Drag.Move(..) to enable or disable dragging.

So first create the drag object as you are already doing:

var drag = new Drag.Move(e, {
    ...
});

And then store a reference of this drag object inside the Element Store for later retrieval.

e.store('Drag', drag);

You can use any key you want here - I've used "Drag".

Then later in the check function, retrieve the drag object, and call attach or detach on it depending on the state of the checkbox.

function check(elem) {
    var drag = elem.retrieve('Drag'); // retrieve the instance we stored before

    if(elem.checked) {
        drag.detach(); // disable dragging
    }
    else {
        drag.attach(); // enable dragging
    }
}

See your example modified to work this the checkbox.

On a side note, if you are retrieving an element by id, you don't need to use $$ as ideally there should only be only element with that id. $$("#dragable") is just too redundant and less performant. Use document.id('dragable') or $("dragable") instead.

0

精彩评论

暂无评论...
验证码 换一张
取 消